我正在尝试对MultiIndex列使用查询。它适用于MultiIndex行,但不适用于该列。是否有一个原因?该文档显示的示例类似于下面的第一个示例,但并不表示它不适用于MultiIndex列。
我知道还有其他方法可以执行此操作,但是我正在尝试使用查询功能
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.random((4,4)))
df.index = pd.MultiIndex.from_product([[1,2],['A','B']])
df.index.names = ['RowInd1', 'RowInd2']
# This works
print(df.query('RowInd2 in ["A"]'))
df = pd.DataFrame(np.random.random((4,4)))
df.columns = pd.MultiIndex.from_product([[1,2],['A','B']])
df.columns.names = ['ColInd1', 'ColInd2']
# query on index works, but not on the multiindexed column
print(df.query('index < 2'))
print(df.query('ColInd2 in ["A"]'))
答案 0 :(得分:0)
您可以使用IndexSlice
df.query('ilevel_0>2')
Out[327]:
ColInd1 1 2
ColInd2 A B A B
3 0.652576 0.639522 0.52087 0.446931
df.loc[:,pd.IndexSlice[:,'A']]
Out[328]:
ColInd1 1 2
ColInd2 A A
0 0.092394 0.427668
1 0.326748 0.383632
2 0.717328 0.354294
3 0.652576 0.520870
答案 1 :(得分:0)
要回答我自己的问题,基于此处的答案,看来根本不应该使用查询(无论使用MultiIndex列)来选择某些列。