[英]Selecting Pandas data by column levels/ axis 1 multi-index
Here is a piece of code that accomplishes part of what I'm trying to do: 这是一段代码,它完成了我正在尝试的部分内容:
selection=df.xs(('year2012','3quarter','A'),level=[0,1,2],axis=1)
How can I make a selection of multiple criteria in each level of axis 1? 如何在轴1的每个级别中选择多个条件? The following seems to be the wrong way to accomplish this.
以下似乎是完成此任务的错误方法。
selection=df.xs(( ['year2012','year2015'] , ['3quarter','4quarter'] , 'A'), level=[0,1,2], axis=1
) selection=df.xs(( ['year2012','year2015'] , ['3quarter','4quarter'] , 'A'), level=[0,1,2], axis=1
)
Thank you 谢谢
Consider the example dataframe df
考虑示例数据帧
df
mux = pd.MultiIndex.from_product([
['year{}'.format(i) for i in range(2010, 2017)],
['{}quarter'.format(i) for i in range(1, 5)],
list('ABCD')
])
df = pd.DataFrame([np.arange(len(mux))], columns=mux)
df
The way to do this is to use pd.IndexSlice
这样做的方法是使用
pd.IndexSlice
l1 = ['year2012','year2015']
l2 = ['3quarter','4quarter']
l3 = 'A'
df.loc[:, pd.IndexSlice[l1, l2, l3]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.