从多索引 DataFrame 中提取数据

dYz*_*dYz 1 python dataframe pandas

我是 pandas 新手,我正在尝试从 MultiIndex'ed DataFrame 中提取数据

pandas 是否可以从 MultiIndex 对象中选择一系列值,例如下面的示例 DataFrame 我想从第一级(bar、baz、foo 和 qux)以及“one”和“所有列的第二级中的“2”。那可能吗?

arrays = [np.array(['bar', 'bar', 'bar', 'baz', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux','qux']),
np.array(['one', 'two','three','one', 'two', 'three','one', 'two','three', 'one', 'two','three'])]

df = pd.DataFrame(randn(12, 6), index=arrays)
                  0         1         2         3         4         5
bar one   -0.031447  0.084358 -0.045284 -0.073702 -0.566905 -0.541734
    two   -0.381897  0.422047 -0.527828  0.419984 -0.920186  0.643190
    three  0.082314  2.584901  1.149755 -0.741753  0.696301 -0.132365
baz one    0.637182 -0.210955 -0.329989  0.021509 -0.483201 -1.194727
    two    3.602497 -0.010458  1.734119 -0.332384  0.135082  0.194316
    three -0.293277 -0.144820  0.155034 -0.490092 -0.800939 -0.286902
foo one    1.244119  0.024739  0.500957  0.774194 -3.344261  1.098748
    two   -2.328298 -0.473493  0.881086  0.548408  0.882422 -0.151467
    three  0.512852  1.687702  0.154186 -0.079843  0.116599 -1.330802
Run Code Online (Sandbox Code Playgroud)

HYR*_*YRY 5

df.reindex(index=["one", "two"], level=1)
Run Code Online (Sandbox Code Playgroud)

输出:

                0         1         2         3         4         5
bar one  0.494206  1.411835  0.047737 -1.750270  0.649225 -0.226546
    two -0.413393  1.686736  0.110594  1.231486  0.135066  2.025476
baz one -1.146431 -0.584855 -1.718917 -0.288630  0.070884 -0.674778
    two  0.957835  1.463544 -0.374227  0.364186  0.259866 -0.019867
foo one  0.300630 -2.648215  0.217727 -1.986657  1.354950 -0.290845
    two  0.046996  1.490452  0.173022 -0.666131 -0.155762 -2.229876
qux one  0.177816 -0.097909  1.360481 -0.619087 -0.026084 -0.512052
    two  0.589484  1.190523  0.759126 -0.380245  1.416895  0.373932
Run Code Online (Sandbox Code Playgroud)