获取新 pandas 数据帧列中行值和行平均值之间的最大相对差值



我想有一个额外的列,其中包含行值的最大相对差值 [-] 和这些行的平均值:

df充满了几年的能源使用数据。 应该让我得到这个的理论公式如下:df['max_rel_dif'] = MAX [ ABS(最高能耗 – 平均能源使用量(, ABS(最低能耗 – 平均能源使用量(]/平均能源使用

初始数据帧:

ID  y_2010   y_2011   y_2012  y_2013  y_2014
0  23   22631  21954.0  22314.0   22032   21843
1  43   27456  29654.0  28159.0   28654    2000
2  36   61200      NaN      NaN   31895    1600
3  87   87621  86542.0  87542.0   88456   86961
4  90   58951  57486.0   2000.0       0       0
5  98   24587  25478.0      NaN   24896   25461

所需数据帧:

ID  y_2010   y_2011   y_2012  y_2013  y_2014  max_rel_dif
0  23   22631  21954.0  22314.0   22032   21843      0.02149
1  43   27456  29654.0  28159.0   28654    2000      0.91373
2  36   61200      NaN      NaN   31895    1600      0.94931
3  87   87621  86542.0  87542.0   88456   86961      0.01179
4  90   58951  57486.0   2000.0       0       0      1.48870
5  98   24587  25478.0      NaN   24896   25461      0.02065

尝试的代码:

import pandas as pd

import numpy as np


df = pd.DataFrame({"ID": [23,43,36,87,90,98],
   
"y_2010": [22631,27456,61200,87621,58951,24587],
   
"y_2011": [21954,29654,np.nan,86542,57486,25478],
    
"y_2012": [22314,28159,np.nan,87542,2000,np.nan],
     
"y_2013": [22032,28654,31895,88456,0,24896,],
           
"y_2014": [21843,2000,1600,86961,0,25461]})


print(df)


a = df.loc[:, ['y_2010','y_2011','y_2012','y_2013', 'y_2014']]


# calculate mean

mean = a.mean(1)

# calculate max_rel_dif
df['max_rel_dif'] = (((df.max(axis=1).sub(mean)).abs(),(df.min(axis=1).sub(mean)).abs()).max()).div(mean)

# AttributeError: 'tuple' object has no attribute 'max'
-> I'm obviously doing the wrong thing with the tuple, I just don't know how to get the maximum values
from the tuples and divide them then by the mean in the proper Phytonic way

我觉得整个函数可以是

s=df.filter(like='y')
s.sub(s.mean(1),axis=0).abs().max(1)/s.mean(1)
0    0.021494
1    0.913736
2    0.949311
3    0.011800
4    1.488707
5    0.020653
dtype: float64

最新更新