Pandas 使用 MultiIndex 对多列进行分组

问题描述 投票:0回答:1

当有一个简单的 2D-DataFrame 时,使用

df.groupby(["x", "y"])
将多个列分组很简单。但是,我有一个带有 MultiIndices 作为索引和列的 DataFrame:

cols = pd.MultiIndex.from_arrays([[*["coords"]*3, *["type"]*3],[ "x", "y", "z", "a", "b", "c"]])
idx = pd.MultiIndex.from_arrays([[*["values"]*6, "meta"], [*range(6), "foo"]])
df = pd.DataFrame([[1,1,1,6,7,3], [1,1,0,1,5,9], [2,1,0,1,8,3], [2,1,0,5,7,2], [3,1,0,6,5,9], [3,1,0,7,4,5], [None, None, None, "bar", "baz", "qux"]], index=idx, columns=cols)


           coords           type          
                x    y    z    a    b    c
values 0      1.0  1.0  1.0    6    7    3
       1      1.0  1.0  0.0    1    5    9
       2      2.0  1.0  0.0    1    8    3
       3      2.0  1.0  0.0    5    7    2
       4      3.0  1.0  0.0    6    5    9
       5      3.0  1.0  0.0    7    4    5
meta   foo    NaN  NaN  NaN  bar  baz  qux

现在我想对坐标

["x", "y"]
进行分组(
"z"
在这种情况下并不重要,可以被丢弃)。我尝试过不同的方法,例如
df.groupby(["x", "y"])
df.groupby(["x", "y"], level=1)
df.groupby([pd.Grouper(level=1, axis=1), "x", "y"])
,但都不起作用。达到这样的结果(通过
.sum()
实现)的正确调用是什么:

    coords        type          
         x    y      a    b    c
0      1.0  1.0      7   12   12
1      2.0  1.0      6   15    5
2      3.0  1.0     13    9   14

是否包含

("meta", "foo")
行对我来说并不重要,添加或删除它应该很容易。

python pandas dataframe multi-index
1个回答
0
投票

您可以提供“完整”列名称:

>>> df.groupby([("coords","x"),("coords","y")]).sum()

                        coords type        
                             z    a   b   c
(coords, x) (coords, y)                    
1.0         1.0            1.0    7  12  12
2.0         1.0            0.0    6  15   5
3.0         1.0            0.0   13   9  14
© www.soinside.com 2019 - 2024. All rights reserved.