首页 > 解决方案 > 熊猫过滤器分组

问题描述

我想过滤此查询中的结果,因此如果可能在一行代码中,表中只有结果 >1。

import pandas as pd 
import numpy as np 
df= pd.DataFrame({'Product':['A','B', 'C','A','B','D'],
                  'Age':[28,39,21,50,35,43], 
                  'Country':['USA','India','Germany','USA','India','India']
                 })
print(df.head())
table=df.groupby(['Product','Country'])['Age'].count()
table

标签: pythonpandasgroup-by

解决方案


让我们链式query方法:

table = (df.groupby(['Product','Country'])['Age'].count()
           .reset_index(name='Count')
           .query('Count > 1'))
table

输出:

  Product Country  Count
0       A     USA      2
1       B   India      2

推荐阅读