0

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?

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That's it. Just that the numpy function for pow() seems to be np.power(). I edited that in your answer.
@tictoc thanks for catching the error (I just rewrote your function with numpy without checking the name of the function). Ps: there is also an other way to do the power: see the edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.