筛选至少有一行满足条件的GroupBy对象

2024-04-25 10:15:41 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有一个测试:

test_df = pd.DataFrame({'Category': ['P', 'P', 'P', 'Q', 'Q', "Q"],
                    'Subcategory' : ['A', 'B', 'C', 'C', 'A', 'B'],
                    'Value' : [2.0, 5., 8., 1., 2., 1.]})

这样做可以:

test_df.groupby(['Category', 'Subcategory'])['Value'].sum()
# Output is this
Category  Subcategory
P         A              2.0
          B              5.0
          C              8.0
Q         A              2.0
          B              1.0
          C              1.0

我要筛选子类别中至少有一个值大于或等于3的类别。这意味着在当前测试中,Q将从过滤器中排除,因为它的任何行都不大于或等于3。但是,如果其中一行是5,那么Q将保留在过滤器中。你知道吗

我试过使用下面的方法,但是它过滤掉了类别“p”中的“A”子类别。你知道吗

test_df_grouped = test_df.groupby(['Category', 'Subcategory'])

test_df_grouped.filter(lambda x: (x['Value'] > 2).any()).groupby(['Category', 'Subcategory'])['Value'].sum()

提前谢谢!你知道吗


Tags: test过滤器dataframedfoutputisvaluethis
2条回答

使用loc

s = test_df.groupby(['Category', 'Subcategory'])['Value'].sum()
s.loc[s[s.ge(3)].index.get_level_values(0).unique()].reset_index()

  Category Subcategory  Value
0        P           A    2.0
1        P           B    5.0
2        P           C    8.0

用途:

mask = (test_df['Category'].isin(test_df.loc[test_df['Value'] >= 3, 'Category'].unique())
a = test_df[mask]
print (a)
  Category Subcategory  Value
0        P           A    2.0
1        P           B    5.0
2        P           C    8.0

首先按条件获取所有Category值:

print (test_df.loc[test_df['Value'] >= 3, 'Category'])
1    P
2    P
Name: Category, dtype: object

要获得更好的性能,请创建unique值,感谢@Sandeep Kadapa:

print (test_df.loc[test_df['Value'] >= 3, 'Category'].unique())
['P']

然后按^{}过滤原始列:

print (test_df['Category'].isin(test_df.loc[test_df['Value'] >= 3, 'Category'].unique()))
0     True
1     True
2     True
3    False
4    False
5    False
Name: Category, dtype: bool

groupby之后用MultiIndex过滤序列的相同解决方案:

s = test_df.groupby(['Category', 'Subcategory'])['Value'].sum()
print (s)
Category  Subcategory
P         A              2.0
          B              5.0
          C              8.0
Q         A              2.0
          B              1.0
          C              1.0
Name: Value, dtype: float64

idx0 = s.index.get_level_values(0)
a = s[idx0.isin(idx0[s >= 3].unique())]
print (a)
Category  Subcategory
P         A              2.0
          B              5.0
          C              8.0
Name: Value, dtype: float64

相关问题 更多 >