沿索引和列对多索引 pandas 数据帧进行切片的通用方法是什么?
文档内容丰富、完整,值得一读( https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html ),并且有许多关于堆栈溢出的答案,它们回答了如何专注于“行”或列(这个答案非常彻底, Select rows in pandas MultiIndex DataFrame )。但是,我想要一个更直接的答案,其中包含同时解决这两个问题的示例。
创建多索引数据框
cols_index = pd.MultiIndex.from_product([['a','b','c'],
['x','y','z']], names=['first','second'])
rows_index = pd.MultiIndex.from_product([['d','e','f'],
['u','v','w']], names=['third','fourth'])
df = pd.DataFrame(np.random.choice(10, (9,9)), index=rows_index, columns=cols_index)
df
Out[161]:
first a b
second c d c d
third e f e f e f e f
fourth fifth
j m 9 8 0 1 5 6 3 5
n 1 2 3 3 5 5 4 2
o 5 2 4 7 3 1 0 4
k m 6 6 3 3 4 4 1 7
n 0 6 0 9 2 3 7 5
o 7 8 0 9 7 8 3 4
l m 4 7 4 3 0 5 6 3
n 0 4 3 9 9 5 8 4
o 0 1 8 0 8 9 4 7
我希望看到沿着索引和列中的级别组合对其进行切片的示例。
最佳答案
Here is my generic solution...
使用 loc 和索引切片器来对索引和列级别进行切片
idx = pd.IndexSlice
选择所有内容 - 请注意“:”对应于索引和列中的级别数
df.loc[idx[:,:], idx[:,:,:]]
Out[251]:
first a b
second c d c d
third e f e f e f e f
fourth fifth
j m 2 9 4 5 6 7 7 5
n 1 4 2 6 8 0 6 3
o 2 4 0 2 1 9 9 4
k m 6 5 0 0 9 3 4 0
n 3 1 6 4 2 3 0 4
o 0 7 1 6 9 7 5 7
l m 2 8 0 8 5 1 8 3
n 7 3 2 6 9 4 1 7
o 6 4 7 9 1 3 3 3
选择特定的“单元格”
df.loc[idx['j','m'], idx['a','c','f']]
Out[252]: 9
从索引中选择一级,从列中选择一级
df.loc[idx[:,'m'], idx[:,'c',:]]
Out[253]:
first a b
second c c
third e f e f
fourth fifth
j m 2 9 6 7
k m 6 5 9 3
l m 2 8 5 1
作为列级别的唯一组合的子集
df.loc[:, idx['b','d','f']]
Out[254]:
fourth fifth
j m 5
n 3
o 4
k m 0
n 4
o 7
l m 3
n 7
o 3
Name: (b, d, f), dtype: int32
索引级别的唯一组合的子集
df.loc[idx['k','o'], :]
Out[255]:
first second third
a c e 0
f 7
d e 1
f 6
b c e 9
f 7
d e 5
f 7
Name: (k, o), dtype: int32
关于python - 从多索引 pandas 数据框中选择索引和列的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57875653/