简体   繁体   中英

Error when applying a function over multiple columns in a pandas dataframe

I am quite new to both python and pandas so maybe I am missing something, but I couldn't find the solution to my problem on the web. I try to run a function that should be applied to summarize values row-wise over three columns of a pandas data frame.The task is exactly the same as described here . However, with the proposed solutions I always get the error:

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

Here is an example of my function and what I am trying to do:

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

I also tried to define the function like this:

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)

But I always get the same error message: 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

What am I doing wrong?

math accepts only scalars, not arrays. Use numpy instead

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 

edit

this also works with numpy arrays

def vector(x, y, z):
    vec=np.sqrt(x**2+y**2+z**2)
    return vec 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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