pandas :当组中的值满足所需条件时,将其从数据中删除 [英] Pandas: remove group from the data when a value in the group meets a required condition

查看:79
本文介绍了 pandas :当组中的值满足所需条件时,将其从数据中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据中和每个组中都有值的分组,我想检查组中的值是否在8以下.如果满足此条件,则将整个组从数据集中删除.

I have groupings of values in the data and within each group, I would like to check if a value within the group is below 8. If this condition is met, the entire group is removed from the data set.

请注意,我所指的值位于分组列的另一列中.

Please note the value I'm referring to lies in another column to the groupings column.

示例输入:

Groups Count
  1      7
  1      11
  1      9 
  2      12
  2      15
  2      21 

输出:

Groups Count
  2      12
  2      15
  2      21 

推荐答案

根据您在问题中描述的内容,只要组中至少有一个小于8的值,则应删除该组.因此,等效的陈述是,只要该组中的最小值低于8,就应删除该组.

Based on what you described in the question, as long as there is at least one value is below 8 within the group, then that group should be dropped. So the equivalent statement is that as long as the minimum value within that group is below 8, that group should be dropped.

通过使用过滤器功能,实际代码只能减少到一行,请参考过滤,您可以使用以下代码:

By using the filter feature, the actual code can be reduced to only one line, please refer to Filtration, you may use the following code:

dfnew = df.groupby('Groups').filter(lambda x: x['Count'].min()>8 )
dfnew.reset_index(drop=True, inplace=True) # reset index
dfnew = dfnew[['Groups','Count']] # rearrange the column sequence
print(dfnew)

Output:
   Groups  Count
0       2     12
1       2     15
2       2     21

这篇关于 pandas :当组中的值满足所需条件时,将其从数据中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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