python - Pandas :过滤计数小于指定值的数据透视表行

标签 python pandas pivot-table

我有一个 pandas 数据透视表,看起来有点像这样:

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

在即将发布的 pandas (11.1) 中,新的 filter method更快更直观地实现这一点:

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

关于python - Pandas :过滤计数小于指定值的数据透视表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17109419/

相关文章:

python - 使用 pdist 在 Python 中使用字符串距离矩阵

python - 将与不同值关联的重复条目转换为包含这些值列表的条目?

python - 从 PyArrow 写入 Parquet 文件时如何指定逻辑类型?

Excel 数据透视表行标签不刷新

sql-server - 对多列进行透视 (T-SQL)

python - DRF - 发布 JSON 对象时日期值出现 KeyError

Python 正则表达式不工作

mysql - 将表列转换为行并使用一个表中的值(如果它不存在于另一个表中)

python - 使用视差图进行距离测量

python-3.x - Python 中的大型 XML 文件解析