Pandas multi-indexed 列的总和

Pandas sum of multi-indexed columns

如果我有一个像这样嵌套 headers 的数据框:

              John          Joan
         Smith,   Jones,    Smith,
Index1     234      432      324
Index2     2987     234      4354

...如何创建一个新列来汇总每行的值? 我试过 df['sum']=df['John']+df['Joan'] 但这导致了这个错误:

ValueError: Wrong number of items passed 3, placement implies 1

舞会,好久没有你的消息了

您想分组,但指定了一个级别和轴。 axis=1 表示您想要对行而不是列求和。 level=0 是列的第一行。

df = pd.DataFrame({
    ('John', 'Smith,'): [234, 2987], 
    ('John', 'Jones,'): [432, 234], 
    ('Joan', 'Smith,'): [324, 4354]}, index=['Index1', 'Index2'])

>>> df.groupby(level=0, axis=1).sum()
        Joan  John
Index1   324   666
Index2  4354  3221

如果我理解正确的话:

...how do I create a new column that sums the values of each row?

解决方案

每一行的总和刚好

df.sum(axis=1)

诀窍是成为一个新专栏。您需要确保您添加的列具有 2 级列标题。

df.loc[:, ('sum', 'sum')] = df.sum(axis=1)

我对此并不满意,但它确实有效。

         Joan   John          sum
       Smith, Jones, Smith,   sum
Index1    324    432    234   990
Index2   4354    234   2987  7575