ValientProcess
ValientProcess

Reputation: 1801

Pandas: Adding column with calculations from other columns

I have a csv with measurements:

YY-MO-DD HH-MI-SS_SSS    |        x          |          y
2015-12-07 20:51:06:608  |        2          |          4
2015-12-07 20:51:07:609  |        3          |          4

and I want to add another column with the square root of the sum of x^2+y^2, z=sqrt(x^2+y^2)

like this:

 YY-MO-DD HH-MI-SS_SSS       |        x          |          y     |     z
    2015-12-07 20:51:06:608  |        2          |          4     |   4.472
    2015-12-07 20:51:07:609  |        3          |          4     |    5

Any ideas?

Thank you !

Upvotes: 5

Views: 10956

Answers (1)

EdChum
EdChum

Reputation: 393973

Use np.sqrt on the result of the squares:

In [10]:
df['z'] = np.sqrt(df['x']**2 + df['y']**2)
df

Out[10]:
   x  y         z
0  2  4  4.472136
1  3  4  5.000000

You can also sum row-wise the result of np.square and call np.sqrt:

In [13]:
df['z'] = np.sqrt(np.square(df[['x','y']]).sum(axis=1))
df

Out[13]:
   x  y         z
0  2  4  4.472136
1  3  4  5.000000

Upvotes: 8

Related Questions