pandas :在一级过滤列 [英] Pandas: Filter columns in one level

查看:71
本文介绍了 pandas :在一级过滤列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有MultiIndex的熊猫数据框.我想删除级别1中所有值大于12的列值.我能做

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], level=1, axis=1, inplace=True)

但是不会删除大于20的值.是否有办法将这些值限制为仅12个?

but that does not remove values greater than 20. Is there a way to limit the values to 12 only?

推荐答案

使用pd.IndexSlice

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

考虑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

然后

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

   a     b   
  5  10 5  10
0  0  1  5  6


caveat
这要求对df.columns进行排序.您可能需要提前排序


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]]

这篇关于 pandas :在一级过滤列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆