Pandas对列使用函数

时间:2018-02-28 12:58:03

标签: pandas

为什么Pandas在尝试将此函数应用于列时会抛出错误?

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))

尝试使用df.apply时,最后一行会出现错误消息。输出是:

    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

1 个答案:

答案 0 :(得分:2)

我认为需要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

但更好的是使用vectorize numpy.cos

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