Calculus
Calculus

Reputation: 781

Pandas apply function against column

Why is Pandas throwing an error when trying to apply this function to a column?

import pandas as pd
import math

data = [
    ['LAT', "LON"],
    [49.00, -83.04],
    [41.00, -83.04],
    [26.00, -83.04],
]
df= pd.DataFrame(data[1:], columns=data[0])

print(df)
print((math.cos(49.00) * 69.172) /.25)


df['LAT'] = df['LAT'].astype(int)
df['test'] = df.apply(lambda t: ((math.cos(t['LAT']) * 69.172) /.25))

The error message occurs on the last line when trying to use df.apply. Output is:

    LAT    LON
0  49.0 -83.04
1  41.0 -83.04
2  26.0 -83.04
83.17034974333946

  File "pandas/_libs/index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 759, in pandas._libs.hashtable.Int64HashTable.get_item
TypeError: an integer is required

Upvotes: 1

Views: 63

Answers (1)

jezrael
jezrael

Reputation: 863501

I think need Series.apply:

df['test'] = df['LAT'].apply(lambda t: ((math.cos(t) * 69.172) /.25))
print (df)
    LAT    LON        test
0  49.0 -83.04   83.170350
1  41.0 -83.04 -273.184930
2  26.0 -83.04  178.994813

But better is use vectorize numpy.cos:

df['test'] = np.cos(df['LAT']) * 69.172 / .25

Upvotes: 2

Related Questions