如果我使用命令
df_extract = df.xs((0,21), level=('ID','JI'), axis=1)
我得到以下结果,它按预期工作。
我现在想知道如何用多个不同的指标实现类似的结果,例如如果我想获得ID = 0且JI = 21 的所有数据,并且 JI = 20,则表示列数会翻倍。
答案 0 :(得分:0)
我认为你需要slicers
:
np.random.seed(1235)
a = ['RX','confidence']
b = range(4)
c = range(22)
mux = pd.MultiIndex.from_product([a,b,c])
df = pd.DataFrame(np.random.randn(5, 176), columns=mux)
print (df)
RX \
0
0 1 2 3 4 5 6
0 0.689382 -0.031712 0.668054 0.488838 -0.679788 -1.307479 1.470304
1 -0.036204 1.160644 -0.732690 1.236523 -3.056192 -0.934713 1.710129
2 1.053523 -0.155585 2.366245 -0.881146 1.020934 -0.864370 -0.296776
3 0.400810 -0.684544 -0.834513 -2.430665 -1.235054 1.267301 0.733521
4 -0.948905 -2.201098 -0.817812 1.668433 -0.262451 -0.898930 -0.322147
... confidence \
... 3
7 8 9 ... 12 13 14
0 -1.231027 0.958775 0.740490 ... -1.566432 -1.100071 0.798843
1 -0.672050 0.266822 1.721244 ... 1.283321 -0.881721 -1.681788
2 -0.516580 1.273032 0.390264 ... 1.509285 0.901942 0.075606
3 0.593818 -0.254829 -0.160123 ... -0.535404 -1.354794 0.981214
4 -1.746534 0.933562 2.149050 ... -2.636260 0.761145 -0.629726
15 16 17 18 19 20 21
0 0.263073 -0.343827 -0.567384 -0.118225 1.285035 -1.111085 -0.696510
1 -1.151469 -0.487992 0.499224 0.613910 -1.581301 -0.354810 1.045596
2 0.248246 -2.444664 0.853859 0.503577 0.804451 -0.684316 1.557988
3 -0.770024 -0.685887 0.767945 -1.050074 0.794344 0.132869 -0.824384
4 -1.983435 0.789378 2.411277 2.603050 0.433517 0.918651 -1.088107
[5 rows x 176 columns]
idx = pd.IndexSlice
df = df.loc[:, idx[:, 0, [20,21]]]
print (df)
RX confidence
0 0
20 21 20 21
0 -0.680341 0.338532 -0.701041 -1.263422
1 -0.571725 0.081422 0.385731 -0.306937
2 0.131121 -0.889890 0.245415 0.686879
3 0.839858 0.145986 -0.391957 1.029721
4 -1.278226 0.877223 -0.579988 -0.398001