【发布时间】:2019-05-06 17:28:14
【问题描述】:
当N > 2时,如何扩展基于前N-1层从DataFrame中选择的逻辑?
例如,考虑一个 DataFrame:
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], :]]
but is cumbersome, especially when the selector needs to be extracted from another DataFrame with a 2-level MultiIndex:
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]] 能够根据第一个排序列的精神级别。
【问题讨论】:
标签: python-3.x pandas multi-index