繁体   English   中英

在熊猫数据框中的多个列上应用函数时出错

[英]Error when applying a function over multiple columns in a pandas dataframe

我对python和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)

但是我总是得到相同的错误消息:追溯(最近一次调用最近):vector2的文件“”的第1行,vector 2的第5行,TypeError:只有length-1数组可以转换为Python标量

我究竟做错了什么?

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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM