Introduction
My code is supposed to import the data from .xlsx files and make calculations based on this. The problem lies in that the unit of each column is saved in the second row of the sheet and is imported as first entry of the data column. Resulting in something like this:
import pandas as pd
import numpy as np
data = pd.DataFrame(data = {'alpha' : ['[°]', 180, 180, 180]})
data['sin'] = np.sin(data['alpha'])
Problem
Because the first cell is str
type, the column becomes object
type. I thought I could solve this problem by rearranging the dataframe by adding the following code between the two lines:
data = data.drop([0]).reset_index(drop = True)
data.astype({'alpha' : 'float64'})
The dataframe now looks like I want it to look and I suppose it should work as intendet, but instead I get an AttributeError and a TypeError:
AttributeError: 'float' object has no attribute 'sin'TypeError: loop of ufunc does not support argument 0 of type float which has no callable sin method
TypeError: loop of ufunc does not support argument 0 of type float which has no callable sin method
Any insight on why I get these errors and how to solve them would be appreciated!
CodePudding user response:
You can use Pandas' conversion function like this:
data = pd.DataFrame(data = {'alpha' : ['[°]', 180, 180, 180]})
data['alpha'] = pd.to_numeric(data['alpha'], errors='coerce')
# is your alpha degrees or radians?
data['sin'] = np.sin(np.deg2rad(data['alpha']))
Output:
alpha sin
0 NaN NaN
1 180.0 1.224647e-16
2 180.0 1.224647e-16
3 180.0 1.224647e-16