2017-09-15 106 views
0

一个数据帧列如下:计算成新列

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

'math.cos'功能不采取系列/ dataframes,它需要的花车,你可以使用'NP。 cos'等? – Zero

回答

0

math.sinmath.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,但它们往往很慢。

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