Reputation: 673
I new to pandas and I'm trying to extract data from a MultiIndex'ed DataFrame
is it possible in pandas to select a range of values from a MultiIndex object, e.g. the example DataFrame below I would like to select all of the values from the first level (bar, baz, foo & qux) and the 'one' and 'two' from the second level for all the columns. is that possible?
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
Upvotes: 1
Views: 248
Reputation: 97261
df.reindex(index=["one", "two"], level=1)
output:
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
Upvotes: 5
Reputation: 40618
I don't think there's an easy way to do this just yet. I think version 0.11 might be addressing this. In the meantime, I find it easiest to just swap the index levels and use .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
Upvotes: 0