我对 python 和 pandas 都很陌生,所以也许我遗漏了一些东西,但我在网上找不到解决我的问题的方法。我尝试运行一个函数,该函数应该应用于在 pandas 数据框的三列上逐行汇总值。任务与此处描述的完全相同。但是,使用建议的解决方案,我总是会收到错误消息:
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)
但我总是收到相同的错误消息: Traceback (last most recent call last): File "", line 1, in File "", line 5, in vector2 TypeError: only length-1 arrays can be convert to Python scalars
我究竟做错了什么?