【问题标题】:Pandas normalise by column on groupbyPandas 在 groupby 上按列标准化
【发布时间】:2021-06-25 10:00:33
【问题描述】:

给定一个熊猫数据框,例如

import pandas as pd

df = pd.DataFrame({'id': ['id1','id1','id2','id2'] , 
                   'x':  [1,2,3,4], 
                   'y':  [10,20,30,40]})

每个数值列可以标准化为单位间隔[0,1]

columns = ['x', 'y']

for column in columns:
    df[column] = (df[column] - df[column].min()) / (df[column].max() - df[column].min())

导致

    id         x         y
0  id1  0.000000  0.000000
1  id1  0.333333  0.333333
2  id2  0.666667  0.666667
3  id2  1.000000  1.000000

但是,如何在每个 id 的每个数字列上应用这种规范化?预期结果将在这个过于简单的示例中

    id         x         y
0  id1  0.000000  0.000000
1  id1  1.000000  1.000000
2  id2  0.000000  0.000000
3  id2  1.000000  1.000000

证明不清楚如何更新每个归一化后的列

df.groupby(['id']).apply(lambda x: ...)

【问题讨论】:

    标签: python pandas pandas-groupby normalize


    【解决方案1】:

    使用GroupBy.transform:

    columns = ['x', 'y']
    g = df.groupby('id')[columns]
    df[columns] = (df[columns] - g.transform('min')) / (g.transform('max') - g.transform('min'))
        
    print (df)
        id    x    y
    0  id1  0.0  0.0
    1  id1  1.0  1.0
    2  id2  0.0  0.0
    3  id2  1.0  1.0
    

    【讨论】:

      【解决方案2】:

      可能不是最好的方法,但如果你的数据框不是很大,那么这样做:

      for column in columns:
          for id in list_of_IDs:
              df.loc[df.loc[id] == i,column] = (df.loc[df.loc[id] == i,column] - df.loc[df.loc[id] == i,column].min()) / df.loc[df.loc[id] == i,column].max() - df.loc[df.loc[id] == i,column].min())
      

      【讨论】:

        【解决方案3】:

        证明不清楚如何更新df.groupby(['id']).apply(lambda x: ...)之后的每个规范化列

        您可以再次apply

        df.groupby(["id"])\
        .apply(lambda id_df: id_df[columns]\
                             .apply(lambda serie: (serie - serie.min()) / (serie.max() - serie.min())))
        

        【讨论】:

          猜你喜欢
          • 2021-10-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-21
          • 2018-09-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-13
          • 1970-01-01
          相关资源
          最近更新 更多