nrc*_*001 10 python grouping dataframe pandas
我在数据和每个组内都有值分组,我想检查组内的值是否低于此值8.如果满足此条件,则从数据集中删除整个组.
请注意我所指的值位于分组列的另一列.
示例输入:
Groups Count
1 7
1 11
1 9
2 12
2 15
2 21
Run Code Online (Sandbox Code Playgroud)
输出:
Groups Count
2 12
2 15
2 21
Run Code Online (Sandbox Code Playgroud)
234*_*DI8 16
根据您在问题中描述的内容,只要组内至少有一个值低于8,就应删除该组.因此,等效声明是,只要该组中的最小值低于8,就应该删除该组.
通过使用过滤器功能,实际代码可以减少到只有一行,请参考过滤,您可以使用以下代码:
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
Run Code Online (Sandbox Code Playgroud)
您可以使用isin,loc并unique与反转掩码选择子集。最后,您可以reset_index:
print df
Groups Count
0 1 7
1 1 11
2 1 9
3 2 12
4 2 15
5 2 21
print df.loc[df['Count'] < 8, 'Groups'].unique()
[1]
print ~df['Groups'].isin(df.loc[df['Count'] < 8, 'Groups'].unique())
0 False
1 False
2 False
3 True
4 True
5 True
Name: Groups, dtype: bool
df1 = df[~df['Groups'].isin(df.loc[df['Count'] < 8, 'Groups'].unique())]
print df1.reset_index(drop=True)
Groups Count
0 2 12
1 2 15
2 2 21
Run Code Online (Sandbox Code Playgroud)