【问题标题】:Getting multiple DataFrame cross-sections获取多个 DataFrame 横截面
【发布时间】:2014-03-25 15:50:58
【问题描述】:

假设我有一个 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 或“三个”的所有条目?

以下内容:

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

没用。

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

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

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我通常使用任何一个

    >>> 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]
    

    【讨论】:

    • 很高兴知道!查询的好例子。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多