pandas - 如何在 Pandas 中聚合子数据帧?

标签 pandas aggregation multi-index

假设我有两级多索引数据框

In [1]: index = pd.MultiIndex.from_tuples([(i,j)  for i in range(3)
      :                                           for j in range(1+i)], names=list('ij') )
      : df = pd.DataFrame(0.1*np.arange(2*len(index)).reshape(-1,2),
      :                   columns=list('xy'), index=index )
      : df
Out[1]:
      x    y
i j
0 0  0.0  0.1
1 0  0.2  0.3
  1  0.4  0.5
2 0  0.6  0.7
  1  0.8  0.9
  2  1.0  1.1

我想在每个子数据帧上运行一个自定义函数:

In [2]: def my_aggr_func(subdf):
      :     return subdf['x'].mean() / subdf['y'].mean()
      :
      : level0 = df.index.levels[0].values
      : pd.DataFrame({'mean_ratio': [my_aggr_func(df.loc[i]) for i in level0]},
      :              index=pd.Index(level0, name=index.names[0]) )
Out[2]:
     mean_ratio
i
0    0.000000
1    0.750000
2    0.888889

有没有一种优雅的方法可以使用 df.groupby('i').agg(__something__) 或类似的东西来做到这一点?

最佳答案

需要GroupBy.apply ,与 DataFrame 一起工作:

df1 = df.groupby('i').apply(my_aggr_func).to_frame('mean_ratio')
print (df1)
   mean_ratio
i            
0    0.000000
1    0.750000
2    0.888889

关于pandas - 如何在 Pandas 中聚合子数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45721046/

相关文章:

python - Pandas - 在循环中迭代索引

python - 使用 pandas 将字符串替换为其自身的较短版本

sql - 如何对 PostgreSQL 中的列的一部分进行分组?

arrays - 明智地聚合数组元素

python - Pandas - 按大小总和对 Multiindex 进行排序

python - 对数据框多索引级别和按列进行排序

python - 如何根据记录中其他 4 个字段的 bool 运算符有效更新数据框中的字段?

python-3.x - 在另一列的指定组中查找另一列中存在重复项的行

elasticsearch - 嵌套过滤器聚合包括 doc_count 中的空文档

python - 使用 IndexSlice 通过 Pandas 过滤多索引数据帧