熊猫数据框将每个组的最大值除以一个函数

时间:2019-07-22 04:36:51

标签: python pandas pandas-groupby

我想将每行除以每组中的最大值。我只为一栏做过,但我也想针对高度和距离做。如何在一项功能中做到这一点?

data = [['1020',12000,100,1.5],
     ['1020',15000,120,0.9],
     ['1020',13000,90,0.8],
     ['1020',10000,110,1],
     ['1030',5000,150,1.2],
     ['1030',8000,160,1.4],
     ['1030',7000,140,1.1],
     ['1000',20000,160,1.4],
     ['1000',40000,140,1.1],
    ] 
    df = pd.DataFrame(data, columns = ['Group_Id', 
    'Price','Height','Distance']) 

    # print dataframe. 
   df

下面我尝试过。但是我怎么写才能将此功能组合成三列呢?

   dist =  df.groupby('Group_Id')['Price'].transform('max')
   df['Price_score'] = dist.sub(df['Price']).div(dist)
   df.head(10)

1 个答案:

答案 0 :(得分:1)

使用groupby.transform而不以以下方式访问任何column

dist =  df.groupby('Group_Id').transform('max')
df.loc[:, df.drop('Group_Id', axis=1).columns] = (dist.sub(df.drop('Group_Id', axis=1))
                                                      .div(dist))

print(df)
  Group_Id     Price    Height  Distance
0     1020  0.200000  0.166667  0.000000
1     1020  0.000000  0.000000  0.400000
2     1020  0.133333  0.250000  0.466667
3     1020  0.333333  0.083333  0.333333
4     1030  0.375000  0.062500  0.142857
5     1030  0.000000  0.000000  0.000000
6     1030  0.125000  0.125000  0.214286
7     1000  0.500000  0.000000  0.000000
8     1000  0.000000  0.125000  0.214286

或者,如果您想保留原始列,请使用:

dist =  df.groupby('Group_Id').transform('max')
df = df.join(dist.sub(df.drop('Group_Id', axis=1)).div(dist).add_suffix('_grp'))

print(df)
  Group_Id  Price  Height  Distance  Price_grp  Height_grp  Distance_grp
0     1020  12000     100       1.5   0.200000    0.166667      0.000000
1     1020  15000     120       0.9   0.000000    0.000000      0.400000
2     1020  13000      90       0.8   0.133333    0.250000      0.466667
3     1020  10000     110       1.0   0.333333    0.083333      0.333333
4     1030   5000     150       1.2   0.375000    0.062500      0.142857
5     1030   8000     160       1.4   0.000000    0.000000      0.000000
6     1030   7000     140       1.1   0.125000    0.125000      0.214286
7     1000  20000     160       1.4   0.500000    0.000000      0.000000
8     1000  40000     140       1.1   0.000000    0.125000      0.214286

print(dist)
   Price  Height  Distance
0  15000     120       1.5
1  15000     120       1.5
2  15000     120       1.5
3  15000     120       1.5
4   8000     160       1.4
5   8000     160       1.4
6   8000     160       1.4
7  40000     160       1.4
8  40000     160       1.4