簡體   English   中英

如何根據其他 dataframe 的條件刪除 pandas 組

[英]How to drop a pandas group based on a condition from other dataframe

我有兩個數據框,看起來像這樣

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

我試圖刪除df1df2中的value低於 10的所有分組名稱(在這種情況下,我想刪除df1['name']='Max'所有行)。

我想要得到的結果是:

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

謝謝!

像這樣:

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
#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
df1['name'].isin(['Max']) # select the df1 which name is 'Max'

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM