简体   繁体   English

熊猫:从列中减去值(以从中查找变化)

[英]Pandas: subtracting value from column (to find variations from it)

I have a dataframe with this type of column: 我有一个带有这种类型的列的数据框:

magnetic_mag
34.451282394
44.81445845
24.833269553
25.032404588
22.027024464

I want to find the variation of every value from 30 (If the value is above 30 so I want to subtract 30 from it and if it's below I want to subtract the value itself from 30), so the output column in the data frame should look like this: 我想找到30中每个值的变化(如果该值大于30,那么我想从中减去30,如果小于30,我想从30中减去值本身),因此数据框中的输出列应该看起来像这样:

magnetic_mag
    4.451282394
    14.81445845
    5.166730447
    4.967595412
    7.972975536

Any easy way to do it with pandas ? 有什么简单的方法可以处理大熊猫吗?

Edit: If I want the values below 30 to be with (-) sign (negative) is it possible? 编辑:如果我希望低于30的值带有(-)号(负号),可以吗? Desired output: 所需的输出:

magnetic_mag
        4.451282394
        14.81445845
        -5.166730447
        -4.967595412
        -7.972975536

Thank you ! 谢谢 !

You can just subtract 30 and call abs : 您可以减去30并调用abs

(df["magnetic_mag"] - 30).abs()
Out[23]: 
0     4.451282
1    14.814458
2     5.166730
3     4.967595
4     7.972976
Name: magnetic_mag, dtype: float64

A variation: 变体:

import numpy as np

np.where(df['magnetic_mag']>30, df['magnetic_mag']-30, 30-df['magnetic_mag'])
#Out[100]: array([  4.45128239,  14.81445845,   5.16673045,   4.96759541,   7.97297554])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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