获取多个DataFrame横截面

时间:2014-03-25 15:50:59

标签: python pandas

假设我有一个MultiIndex DataFrame:

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                          'foo', 'bar', 'foo', 'foo'],  
                   'B' : ['one', 'one', 'two', 'three',
                          'two', 'two', 'one', 'three'],
                   'C' : randn(8), 'D' : randn(8)})

df = df.set_index(['A', 'B']).sort_index()
                  C         D
A   B                        
bar one    0.052069 -0.541728
    three -1.703340  0.369047
    two   -0.221340  1.281790
foo one    0.219942  0.093917
    one   -2.531077  0.445473
    three  0.243135 -1.730576
    two   -1.464053  1.241126
    two   -0.846171 -1.444660

如何检索level=B two或“3”的所有条目?

以下内容:

df.xs(['two', 'three'], level='B') 

不起作用。

但有趣的是,我一个接一个地做(?),即:

   df.xs(['two'], level='B') 

   df.xs(['three'], level='B') 

1 个答案:

答案 0 :(得分:3)

我通常使用

>>> df.query("B in ['two', 'three']")
                  C         D
A   B                        
bar three  1.493379 -0.323488
    two    1.122867 -0.338157
foo three  0.228644 -0.343841
    two   -1.283377  0.724590
    two   -0.330542  1.646273

[5 rows x 2 columns]

>>> df[df.index.get_level_values('B').isin(["two", "three"])]
                  C         D
A   B                        
bar three  1.493379 -0.323488
    two    1.122867 -0.338157
foo three  0.228644 -0.343841
    two   -1.283377  0.724590
    two   -0.330542  1.646273

[5 rows x 2 columns]
相关问题