Skip to main content
 首页 » 编程设计

python之Pandas Groupby 行数不佳

2024年10月17日9qlqwjy

有没有办法强制 pandas.groupby 返回一个 DataFrame?这是说明我的问题的示例:

玩具数据框:

df = pd.DataFrame(data=dict(a=[1, 1, 1, 2, 2, 2, 3, 3, 3],  
                            b=[1, 1, 1, 2, 2, 2, 4, 4, 4]) 

此函数按预期返回数据框:

def fcn_good(d): 
    return pd.Series(data=dict(mean=d.b.mean(), std=d.b.std())) 
print(df.groupby('a').apply(fcn_good)) 

有输出

   mean  std 
a 
1   1.0  0.0 
2   2.0  0.0 
3   4.0  0.0 

问题来了。在我的真实代码中,一些groupby键在计算过程中会失败。我想要的输出是:

   mean  std 
a 
1   1.0  0.0 
2   NaN  NaN 
3   4.0  0.0 

但是,这段代码

def fcn_bad(d): 
    if int(d.a.unique()[0]) == 2: # Simulate failure 
        return pd.Series() 
    return pd.Series(data=dict(mean=d.b.mean(), std=d.b.std())) 
print(df.groupby('a').apply(fcn_bad)) 

改为返回一个系列:

a 
1  mean    1.0 
   std     0.0 
3  mean    4.0 
   std     0.0 
dtype: float64 

有人知道如何让它工作吗?

请您参考如下方法:

您可以使用 unstack和 reindex通过 unique a 列的值,因为 groupby按 a 列:

def fcn_bad(d): 
    if int(d.a.unique()[0]) == 2: # Simulate failure 
        return pd.Series() 
    return pd.Series(data=dict(mean=d.b.mean(), std=d.b.std())) 
print(df.groupby('a').apply(fcn_bad).unstack().reindex(df.a.unique())) 
   mean  std 
a            
1   1.0  0.0 
2   NaN  NaN 
3   4.0  0.0 

如果将 index 添加到 Series 中,pd.Series(index=['mean', 'std']),返回DataFrame:

def fcn_bad(d): 
    if int(d.a.unique()[0]) == 2: # Simulate failure 
        return pd.Series(index=['mean','std']) 
    return pd.Series(data=dict(mean=d.b.mean(), std=d.b.std())) 
print(df.groupby('a').apply(fcn_bad)) 
   mean  std 
a            
1   1.0  0.0 
2   NaN  NaN 
3   4.0  0.0