简体   繁体   中英

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 !

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

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