selecting from multi-index pandas
I have a multi-index data frame with columns 'A' and 'B'.
Is there is a way to select rows by filtering on one column of the multi-index without reseting the index to single column index.
# has multi-index (A,B) df #can i do this? I know this doesnt work because index is multi-index so I need to specify a tuple df.ix[df.A ==1]
One way is to use the
get_level_values Index method:
In : df Out: 0 A B 1 4 1 2 5 2 3 6 3 In : df.iloc[df.index.get_level_values('A') == 1] Out: 0 A B 1 4 1
In 0.13 you'll be able to use
df.xs(1, level='A', drop_level=False) # axis=1 if columns
Note: if this were column MultiIndex rather than index, you could use the same technique:
In : df1 = df.T In : df1.iloc[:, df1.columns.get_level_values('A') == 1] Out: A 1 B 4 0 1