【问题标题】:Python pandas groupby: how to use variables in different columns to create a new onePython pandas groupby:如何使用不同列中的变量来创建一个新列
【发布时间】:2023-02-26 16:01:52
【问题描述】:

考虑以下DataFrame:

df = pd.DataFrame({'c0':['1980']*3+['1990']*2+['2000']*3,
                   'c1':['x','y','z']+['x','y']+['x','y','z'],
                   'c2':range(8)  })

     c0 c1  c2
0  1980  x   0
1  1980  y   1
2  1980  z   2
3  1990  x   3
4  1990  y   4
5  2000  x   5
6  2000  y   6
7  2000  z   7

我想使用 pandas 的 groupby 而不是 c0 来执行以下操作:

  1. 根据c0(注明年份)对行进行分组。
  2. 在每组中,从c2的值中减去y(在c1中)的c2的值。
  3. 添加一个新列c3 收集这些值。

    最后的结果是

         c0 c1  c2  c3
    0  1980  x   0  -1
    1  1980  y   1   0
    2  1980  z   2   1
    3  1990  x   3  -1
    4  1990  y   4   0
    5  2000  x   5  -1
    6  2000  y   6   0
    7  2000  z   7   1
    

    我能够在没有 groupby 的情况下得到结果,如下所示:

    dic = {}
    
    for yr in df['c0'].unique():
        
        cond1 = ( df['c0']==yr )
        tmp = df.loc[cond1,:].copy()
        
        cond2 = ( tmp['c1']=='y' )
        val = tmp.loc[cond2,'c2'].to_numpy()
        
        tmp['c3'] = tmp['c2'] - val
        
        dic[yr] = tmp
    
    
    pd.concat([dic['1980'],dic['1990'],dic['2000']])
    

    它有效但看起来不太好。我试过transform和apply为groupby,但无法弄清楚。任何帮助,将不胜感激。

【问题讨论】:

    标签: python pandas dataframe group-by


    【解决方案1】:

    在使用 where 隐藏组的所有非 y 行后,您可以使用 transform 广播 y 值:

    df['c3' ] = df['c2'] - df.where(df['c1'] == 'y').groupby(df['c0'])['c2'].transform('max')
    print(df)
    
    # Output
         c0 c1  c2   c3
    0  1980  x   0 -1.0
    1  1980  y   1  0.0
    2  1980  z   2  1.0
    3  1990  x   3 -1.0
    4  1990  y   4  0.0
    5  2000  x   5 -1.0
    6  2000  y   6  0.0
    7  2000  z   7  1.0
    

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 2021-07-16
      相关资源
      最近更新 更多