如何根据其他数据框的条件删除熊猫组

时间:2020-05-17 09:58:21

标签: python pandas dataframe pandas-groupby

我有两个看起来像这样的数据框

df1 =
   name   color
0  John   Blue
1  John   Red
2  Lucy   Green
3  Lucy   Blue
4  Max    Blue
2  Max    White

df2 =
   name   value
0  John   15
1  Lucy   20
2  Max    5

我正在尝试删除df1value的{​​{1}}在低于10 df2中的所有分组名称(在这种情况下,我想删除df1['name']='Max'的所有行)。

我想要得到的结果是:

df1 =
   name   color
0  John   Blue
1  John   Red
2  Lucy   Green
3  Lucy   Blue

谢谢!

3 个答案:

答案 0 :(得分:1)

赞:

In [731]: res = pd.merge(df1, df2, on='name')
In [736]: res[res['value'].ge(10)][['name','color']]

Out[736]: 
   name  color
0  John   Blue
1  John    Red
2  Lucy  Green
3  Lucy   Blue

答案 1 :(得分:1)

#get names that are greater than or equal to 10
filtr = df2.loc[df2.value.ge(10),'name']

#extract names that match filtr

df1.loc[df1.name.isin(filtr)]

    name    color
0   John    Blue
1   John    Red
2   Lucy    Green
3   Lucy    Blue

答案 2 :(得分:0)

df1['name'].isin(['Max']) # select the df1 which name is 'Max'

df1=df1[~df1['name'].isin(['Max'])] # reverse select the other elements.