在pandas DataFrame中对多列应用函数时出错
我刚接触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 (most recent call last): File "", line 1, in File "", line 5, in vector2 TypeError: only length-1 arrays can be converted to Python scalars
我到底哪里做错了呢?
1 个回答
1
math
这个库只能处理单个数字,不能处理数组。建议使用 numpy
来处理数组。
import numpy as np
# my function
def vector(x, y, z):
vec=np.sqrt(np.power(x,2)+np.power(y,2)+np.power(z,2))
return vec
补充说明
使用 numpy
数组也可以正常工作。
def vector(x, y, z):
vec=np.sqrt(x**2+y**2+z**2)
return vec