0

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!

Magnus
  • 15
  • 4
  • `data['alpha'] = pd.to_numeric(data['alpha'], errors='coerce')`. – Quang Hoang Oct 28 '21 at 13:58
  • 1
    *"Any insight on why I get these errors ..."* See https://stackoverflow.com/questions/47208473/attributeerror-numpy-float64-object-has-no-attribute-log10/47208873#47208873 (replace `numpy.log10` with `numpy.sin`); the solution there or @QuangHoang's comment and answer provide ways to avoid the error. – Warren Weckesser Oct 28 '21 at 15:12
  • @WarrenWeckesser Thanks a lot, that really helped! Great explanation of the problem! – Magnus Oct 29 '21 at 09:04

1 Answers1

0

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
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • Thanks a lot, that worked wonderfully! I do get handed alpha in degrees but in my actual code I convert it to rads, I just forgot to add the conversion to my minimal example. – Magnus Oct 29 '21 at 09:06