数据框列如下所示:
VALUE
1
2
3
4
5
...
40
我想为这样的eah值生成两个新列:
df['VALUE1'] = math.cos(df['VALUE'] * 2 * math.pi / 48)
df['VALUE2'] = math.sin(df['VALUE'] * 2 * math.pi / 48)
但我的剧本崩溃没有给出任何错误......
结果应该是这样的:
VALUE VALUE1 VALUE2
1 ... ...
2 ... ...
3
4
5
...
40 ... ...
问题是什么?
答案 0 :(得分:0)
math.sin
和math.cos
不接受系列节目。使用numpy
,矢量方法很快。
In [511]: df = pd.DataFrame({'VALUE': range(1, 41)})
In [512]: df['VALUE1'] = np.cos(df['VALUE'] * 2 * np.pi /48)
In [513]: df['VALUE2'] = np.sin(df['VALUE'] * 2 * np.pi /48)
In [514]: df.head()
Out[514]:
VALUE VALUE1 VALUE2
0 1 0.991445 0.130526
1 2 0.965926 0.258819
2 3 0.923880 0.382683
3 4 0.866025 0.500000
4 5 0.793353 0.608761
你可以使用apply
,但它们往往很慢。
答案 1 :(得分:0)
你试过申请吗?
df['VALUE1'] = df['VALUE'].apply(lambda x: math.cos(x * 2 * math.pi / 48))
df['VALUE2'] = df['VALUE'].apply(lambda x: math.sin(x * 2 * math.pi / 48))
答案 2 :(得分:0)
使用Numpy函数,因为它们可以使用向量(列)而不是math
In [23]: df = df.assign(VALUE1=np.cos(df['VALUE'] * 2 * np.pi / 48),
VALUE2=np.sin(df['VALUE'] * 2 * np.pi / 48))
In [24]: df
Out[24]:
VALUE VALUE1 VALUE2
0 1 0.991445 0.130526
1 2 0.965926 0.258819
2 3 0.923880 0.382683
3 4 0.866025 0.500000
4 5 0.793353 0.608761
5 40 0.500000 -0.866025