我是pandas的新手,我正在尝试从MultiIndex的DataFrame中提取数据
是否可以在pandas中从MultiIndex对象中选择一系列值,例如:我想在下面的示例DataFrame中选择第一级(bar,baz,foo和qux)的所有值以及所有列的第二级中的“one”和“two”。那可能吗?
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
答案 0 :(得分:4)
df.reindex(index=["one", "two"], level=1)
输出:
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
答案 1 :(得分:0)
我认为还没有一种简单的方法可以做到这一点。我认为版本0.11可能正在解决这个问题。与此同时,我发现最简单的方法是交换索引级别并使用.ix
:
In [30]: df.swaplevel(1,0).ix[['one','two']]
Out[30]:
0 1 2 3 4 5
one bar -0.388720 -0.265593 -0.625708 -0.372266 0.425832 1.180458
two bar -2.000612 -0.308223 0.236815 0.327834 -0.837164 -0.525281
one baz 0.039961 1.821628 -0.681662 -0.300518 0.495441 1.204195
two baz -0.243946 0.757397 -1.157399 0.044435 0.325952 -1.613384
one foo -0.322431 0.539729 -0.081879 1.129230 -0.324549 -1.252578
two foo 1.127411 -1.957569 -0.284485 0.604807 -0.326727 -1.025945
one qux -0.217390 -3.194743 0.939121 -0.741615 -1.640926 -0.157857
two qux 0.513316 1.568216 -1.702408 0.955211 -0.017799 -0.718302