对重复的多索引值求和的优雅方法

2024-04-25 23:43:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有多层次多重索引的数据帧。在

我知道多重索引中存在重复项(因为我不关心底层数据库关心的区别)

我想对这些重复项求和:

>>> x = pd.DataFrame({'month':['Sep', 'Sep', 'Oct', 'Oct'], 'day':['Mon', 'Mon', 'Mon', 'Tue'], 'sales':[1,2,3,4]})
>>> x
   day month  sales
0  Mon   Sep      1
1  Mon   Sep      2
2  Mon   Oct      3
3  Tue   Oct      4
>>> x = x.set_index(['day', 'month'])
           sales
day month       
Mon Sep        1
    Sep        2
    Oct        3
Tue Oct        4

给我

^{pr2}$

对于一个类似的问题,有人提出了如下建议:

df.groupby(level=df.index.names).sum()

但在我看来,这并没有让好的Python代码'readability counts' criterion失败。在

有没有人知道一种更具人类可读性的方法?在


Tags: 数据数据库dfindexoctseppdsales