Wes*_*ith 5 python slice multi-index dataframe pandas
我有以下使用三级MultiIndex的DataFrame:
In [1]: iterables = [[1, 2], ['foo', 'bar'], ['one', 'two']]
...: midx = pd.MultiIndex.from_product(iterables)
...: df = pd.DataFrame(np.random.randn(8), index=midx)
...: df
Out[1]:
0
1 foo one -0.217594
two -1.361612
bar one 2.477790
two 0.874409
2 foo one 0.403577
two 0.076111
bar one 1.423512
two 0.047898
Run Code Online (Sandbox Code Playgroud)
我想对索引进行切片,以便保留所有第一级,而仅保留第二级('foo', 'one')和第二级的以下组合:和('bar', 'two')。也就是说,我希望我的输出看起来像这样:
0
1 foo one -0.217594
bar two 0.874409
2 foo one 0.403577
bar two 0.047898
Run Code Online (Sandbox Code Playgroud)
是否可以使用诸如之类的属性在一行中执行此操作.loc?
我知道我可以使用该.xs函数分别截取所需组合的横截面,但我希望使用更短,更像切片的语法。具体来说,对于我的用例而言,单线很重要。
似乎以下应该工作:
df.loc[[(slice(None), 'foo', 'one'), (slice(None), 'bar', 'two')]]
Run Code Online (Sandbox Code Playgroud)
但这导致了TypeError: unhashable type: 'slice'。
您可以通过首先删除第一个索引级别然后使用pd.Index.isin元组列表来构造布尔掩码:
df_masked = df[df.index.droplevel(0).isin([('foo', 'one'), ('bar', 'two')])]
print(df_masked)
0
1 foo one 1.510316
bar two 0.260862
2 foo one 0.813745
bar two 0.023386
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
258 次 |
| 最近记录: |