0
应用在多个列的功能时,我很新的Python和大熊猫所以也许我失去了一些东西,但我无法在网上找到解决我的问题。我尝试运行一个函数,该函数应用于在一列熊猫数据框的三列上逐行汇总值。该任务与描述的here完全相同。然而,所提出的解决方案,我总是得到错误:错误的大熊猫数据帧
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in vecSd
TypeError: only length-1 arrays can be converted to Python scalars
这里是我的函数的例子,我想做的事:
import pandas as pd
from math import sqrt, pow
# my function
def vector(x, y, z):
vec=sqrt(pow(x,2)+pow(y,2)+pow(z,2))
return vec
# my data frame looks something like this
df=pd.DataFrame({'x':[12,53,-3,-41], 'y':[74,-45,25,-21], 'z':[-2,-64,-12,65]})
# this is the call
vector(df['x'],df['y'],df['z'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in vecSd
TypeError: only length-1 arrays can be converted to Python scalars
我也试图这样定义功能:
def vector2(df):
x=df['x']
y=df['y']
z=df['z']
vec=sqrt(pow(x,2)+pow(y, 2)+pow(z, 2))
return vec
vector2(df)
但我总是得到同样的错误信息: 回溯(最近通话最后一个): 文件 “”,1号线,在 文件“”,第5行,在vector2中 TypeError:只能将长度为1的数组转换为Python标量
我在做什么错?
谢谢!而已。只是pow()的numpy函数似乎是np.power()。我在你的回答中编辑了它。 – tictoc 2013-02-22 12:42:44
@tictoc感谢您捕捉错误(我只是用numpy重写了你的函数,而没有检查函数的名字)。 Ps:还有另外一种方法来做'power':看编辑 – 2013-02-22 16:30:16