find magnitude of 3 dimensional vectors with python

Viewed 157

I am trying to create a new column in DataFrame by finding magnitude of other three columns but got this error.

TypeError: cannot convert the series to <class 'float'>

Any idea to solve this?

df = pd.read_csv('./data/all.csv')
df['f_magni'] = math.sqrt( (df['fx'])**2 + (df['fz'])**2 + (df['fy'])**2)

It worked with normal calculation but it doesn't work with the above process.

My csv has positive, negative numbers with floats and integers.

Can I get some help here?

2 Answers

You could use numpy.sqrt on the Series object:

import numpy as np
df['f_magni'] = np.sqrt(df['fx']**2 + df['fz']**2 + df['fy']**2)

or just use pow function:

df['f_magni'] = (df['fx']**2 + df['fz']**2 + df['fy']**2).pow(1/2)
Related