当n>2时,如何扩展基于前n-1层从数据帧中选择的逻辑?
例如,考虑一个数据帧:
midx = pd.MultiIndex.from_product([[0, 1], [10, 20, 30], ["a", "b"]])
df = pd.DataFrame(1, columns=midx, index=np.arange(3))
In[11]: df
Out[11]:
0 1
10 20 30 10 20 30
a b a b a b a b a b a b
0 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1
2 1 1 1 1 1 1 1 1 1 1 1 1
在这里,很容易选择0或1位于第一级的列:
df[[0, 1]]
但同样的逻辑并没有扩展到选择第一级为0或1,第二级为10或20的列:
In[13]: df[[(0, 10), (0, 20), (1, 10), (1, 20)]]
ValueError: operands could not be broadcast together with shapes (4,2) (3,) (4,2)
以下工作:
df.loc[:, pd.IndexSlice[[0, 1], [10, 20], :]]
但是很麻烦,特别是当需要从另一个具有2级多索引的数据帧中提取选择器时:
idx = df.columns.droplevel(2)
In[16]: idx
Out[16]:
MultiIndex(levels=[[0, 1], [10, 20, 30]],
labels=[[0, 0, 0, 0, 0, 0, 1, 1, 1, ... 1, 2, 2]])
In[17]: df[idx]
ValueError: operands could not be broadcast together with shapes (12,2) (3,) (12,2)
编辑:
理想情况下,我也希望能够以这种方式对列进行排序,而不仅仅是选择它们—同样,本着
df[[1, 0]]
能够根据第一级对列进行排序。