【问题标题】:Dividing columns of a data frame group-wise?按组划分数据框的列?
【发布时间】:2023-03-08 20:55:01
【问题描述】:

我有一个 df:

temp = pd.DataFrame({'Y': ['A', 'B', 'B', 'A', 'B'],
                    'Z': [10, 5, 6, np.nan, 12],
                                        })

我将 Y 设置为索引,然后按组计算计数和大小:

temp.sort('Y', inplace=True)
temp.set_index('Y', inplace=True, drop=False)
temp.sort_index( inplace=True)

temp['n_obs'] = temp.groupby(by='Y')['Z'].transform('size')
temp['valid'] = temp.groupby(by='Y')['Z'].transform('count')

这会产生:

   Y     Z  n_obs  valid
Y                       
A  A  10.0    2.0    1.0
A  A   NaN    2.0    1.0
B  B   5.0    3.0    3.0
B  B   6.0    3.0    3.0
B  B  12.0    3.0    3.0

现在,我想将 valid 除以 n-obs 分组:

temp['New']=temp.groupby(by='Y').apply(lambda x: (x['valid'] / x['n_obs']))

但我收到此错误:

Exception: cannot handle a non-unique multi-index!

请解决?

【问题讨论】:

    标签: python pandas indexing data-manipulation


    【解决方案1】:

    我觉得你可以用两次reset_index:

    temp.sort_values('Y', inplace=True)
    temp.set_index('Y', inplace=True, drop=False)
    temp.sort_index( inplace=True)
    
    temp['n_obs'] = temp.groupby(by='Y')['Z'].transform('size')
    temp['valid'] = temp.groupby(by='Y')['Z'].transform('count')
    
    temp.reset_index(drop=True, inplace=True)
    
    temp['New'] = temp.groupby(by='Y')
                      .apply(lambda x: (x['valid'] / x['n_obs']))
                      .reset_index(drop=True, level=0)
    print (temp) 
       Y     Z  n_obs  valid  New
    0  A  10.0    2.0    1.0  0.5
    1  A   NaN    2.0    1.0  0.5
    2  B   5.0    3.0    3.0  1.0
    3  B   6.0    3.0    3.0  1.0
    4  B  12.0    3.0    3.0  1.0
    

    但如果省略 groupby 并仅划分列,结果似乎相同:

    temp.sort_values('Y', inplace=True)
    temp.set_index('Y', inplace=True, drop=False)
    temp.sort_index( inplace=True)
    
    temp['n_obs'] = temp.groupby(by='Y')['Z'].transform('size')
    temp['valid'] = temp.groupby(by='Y')['Z'].transform('count')
    
    
    temp['New'] = temp['valid'] / temp['n_obs']
    print (temp) 
       Y     Z  n_obs  valid  New
    Y                            
    A  A  10.0    2.0    1.0  0.5
    A  A   NaN    2.0    1.0  0.5
    B  B   5.0    3.0    3.0  1.0
    B  B   6.0    3.0    3.0  1.0
    B  B  12.0    3.0    3.0  1.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2019-06-28
      • 2018-11-10
      • 2014-12-26
      • 1970-01-01
      • 2021-10-01
      相关资源
      最近更新 更多