我已经使用 Pandas MultiIndex Dataframes 几周了,我感觉我并没有真正理解 GroupBy 对象背后的直觉,尤其是组的选择。
让我们以这段代码为例:
import numpy as np
import pandas as pd
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.Series(np.random.randn(8), index=index)
df = pd.DataFrame(np.random.randn(8, 4), index=arrays)
df.groupby(level=0).first()
最后一行的输出是这样的:
0 1 2 3
bar 1.612350 -0.019424 -0.088925 -0.188864
baz 2.752485 -1.011006 0.249788 1.106547
foo 1.313016 0.716512 0.550851 -1.532394
qux 1.505173 0.758075 1.360808 1.261204
但是,这种行为在我看来没有多大意义,因为它给了我第一组,就好像我会按第二级分组一样。我对上面代码的期望是:
0 1 2 3
one 1.612350 -0.019424 -0.088925 -0.188864
two 0.434829 1.698503 -0.213425 0.329733
到目前为止,我通过这样做实现了我想要的:
list(df.groupby(level=0))[0][1]
但是,这看起来并不意味着要以这种方式完成。
不知何故,我似乎对 GroupBy 对象抱有错误的期望。也许有人可以帮助我解决我的困惑:)。
附加信息: 我不是在寻找特定的解决方案,如何获得“第一组”,因为我已经通过从对象创建列表来获得它。我的问题是关于 GroupBy 对象的理解以及它为什么选择第一个(或任何其他组)的方式。
请您参考如下方法:
你在寻找多索引切片吗?
df.loc[pd.IndexSlice['bar',:],:]
Out[319]:
0 1 2 3
bar one 0.807706 0.07296 0.638787 0.329646
two -0.497104 -0.75407 -0.943406 0.484752
