pandas :过滤计数小于指定值的数据透视表行 [英] Pandas: Filtering pivot table rows where count is fewer than specified value

查看:80
本文介绍了 pandas :过滤计数小于指定值的数据透视表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的熊猫数据透视表:

I have a pandas pivot table that looks a little like this:

C             bar       foo
A     B                    
one   A -1.154627 -0.243234
three A -1.327977  0.243234
      B  1.327977 -0.079051
      C -0.832506  1.327977  
two   A  1.327977 -0.128534
      B  0.835120  1.327977
      C  1.327977  0.838040

我希望能够过滤掉A列少于B列2行的行,以便上面的表格可以过滤A =一:

I'd like to be able to filter out rows where column A has fewer than 2 rows in column B, so that the table above would filter A = one:

C             bar       foo
A     B                    
three A -1.327977  0.243234
      B  1.327977 -0.079051
      C -0.832506  1.327977  
two   A  1.327977 -0.128534
      B  0.835120  1.327977
      C  1.327977  0.838040

我该怎么做?

推荐答案

一行:

In [64]: df[df.groupby(level=0).bar.transform(lambda x: len(x) >= 2).astype('bool')]
Out[64]: 
              bar       foo
two   A  0.944908  0.701687
      B -0.204075  0.713141
      C  0.730844 -0.022302
three A  1.263489 -1.382653
      B  0.124444  0.907667
      C -2.407691 -0.773040

在即将发布的熊猫(11.1)中,新的 方法可以更快,更直观地实现这一目标:

In the upcoming release of pandas (11.1), the new filter method achieves this faster and more intuitively:

In [65]: df.groupby(level=0).filter(lambda x: len(x['bar']) >= 2)
Out[65]: 
              bar       foo
three A  1.263489 -1.382653
      B  0.124444  0.907667
      C -2.407691 -0.773040
two   A  0.944908  0.701687
      B -0.204075  0.713141
      C  0.730844 -0.022302

这篇关于 pandas :过滤计数小于指定值的数据透视表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆