过滤和选择使用python pandas制作的数据透视表

ale*_*hli 7 python indexing pivot pivot-table pandas

我正在努力使用Python pandas包中的层次索引.具体来说,我不明白如何在旋转后过滤比较行中的数据.

以下是文档中的示例表:

import pandas as pd
import numpy as np

In [1027]: df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 6,
                              'B' : ['A', 'B', 'C'] * 8,
                              'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4,
                              'D' : np.random.randn(24),
                              'E' : np.random.randn(24)})

In [1029]: pd.pivot_table(df, values='D', rows=['A', 'B'], cols=['C'])
Out[1029]: 
    C             bar       foo
    A     B                    
    one   A -1.154627 -0.243234
          B -1.320253 -0.633158
          C  1.188862  0.377300
    three A -1.327977       NaN
          B       NaN -0.079051
          C -0.832506       NaN
    two   A       NaN -0.128534
          B  0.835120       NaN
          C       NaN  0.838040
Run Code Online (Sandbox Code Playgroud)

我想分析如下:

1)在列属性上过滤此表,例如选择带负数的行foo:

    C             bar       foo
    A     B                    
    one   A -1.154627 -0.243234
          B -1.320253 -0.633158
    three B       NaN -0.079051
    two   A       NaN -0.128534
Run Code Online (Sandbox Code Playgroud)

2)比较B不同A系列组之间的剩余系列值?我不确定如何访问此信息:{'one':['A','B'], 'two':['A'], 'three':['B']}并确定哪些系列B值对于每个键是唯一的,或在多个键组中看到的等等

有没有办法在数据透视表结构中直接执行此操作,还是需要将其转换回pandas dataframe

更新: 我认为这段代码是朝着正确方向迈出的一步.它至少让我可以访问此表中的各个值,但我仍然在对系列值进行硬编码:

table = pivot_table(df, values='D', rows=['A', 'B'], cols=['C'])
table.ix['one', 'A']
Run Code Online (Sandbox Code Playgroud)

Cha*_*She 11

数据透视表返回一个DataFrame,因此您可以通过执行以下操作进行简单过滤:

In [15]: pivoted = pivot_table(df, values='D', rows=['A', 'B'], cols=['C'])

In [16]: pivoted[pivoted.foo < 0]
Out[16]: 
C             bar       foo
A     B                    
one   A -0.412628 -1.062175
three B       NaN -0.562207
two   A       NaN -0.007245
Run Code Online (Sandbox Code Playgroud)

你可以使用类似的东西

pivoted.ix['one']
Run Code Online (Sandbox Code Playgroud)

选择所有A系列组

要么

pivoted.ix['one', 'A']
Run Code Online (Sandbox Code Playgroud)

选择不同的A和B系列组

  • 让我感到困惑的是,当我尝试`pivoted.dtypes`时,我看到C列的信息,但我想查看A和B列.我希望有一种简单的方法可以获得每个A值的B值,如'{'one':['A','B'],'two':['A'],'three': ['B']}`但是在pandas文档中我没有看到类似的东西 (2认同)