Skip to content Skip to sidebar Skip to footer

Pandas: Filter Columns In One Level

I have a pandas dataframe with a MultiIndex. I want to drop all the column values in level 1 that have value greater than 12. I can do df.drop([13, 14, 15, 16, 17, 18, 19, 20], lev

Solution 1:

using pd.IndexSlice

df.loc[:, pd.IndexSlice[:, :12]]

consider df

mux = pd.MultiIndex.from_product([list('ab'), range(5,30,5)])
df = pd.DataFrame([np.arange(10)], columns=mux)
print(df)

   a              b            
  5  10 15 20 25 5  10 15 20 25
0  0  1  2  3  4  5  6  7  8  9

Then

df.loc[:, pd.IndexSlice[:, :12]]

   a     b   
  5  10 5  10
0  0  1  5  6

caveat
This requires that df.columns is sorted. You may need to sort ahead of time

df.sort_index(axis=1).loc[:, pd.IndexSlice[:, :12]]

Post a Comment for "Pandas: Filter Columns In One Level"