![](/img/trans.png)
[英]Remove all rows that contains the IDs in column1 that have at least one specific value on another specific column2 in a Python Dataframe
[英]How to keep multiple rows if they have the same value within a column AND at least one of them contains a string in another column
df[df['col1'].isin(df[df['col2'] == 'red']['col1'])]
col1 col2
0 1 red
1 1 yellow
2 1 green
7 3 red
8 3 pink
9 3 green
您的意思是“紅色”在 Col1 中的值為 1 和 3,因此您希望在 Col1 中保留所有值為 1 和 3 的行嗎? 你可以試試這個:
df[df['Col1'].isin(df['Col1'][df['Col2']=='red'])]
為了解釋,我使用過濾器來提取相關行:
filter = df['Col1'][df['Col2']=='red']
df1 = df[df['Col1'].isin(filter)]
print(df1)
Output
Col1 Col2
0 1 red
1 1 yellow
2 1 green
6 3 red
7 3 pink
8 3 green
使用 Groupby 並檢查組中 COL2 中的任何行是否為紅色
df[df.groupby("COL1").COL2.transform(lambda x: x.eq("red").any())]
Output
COL1 COL2
0 1 red
1 1 yellow
2 1 green
7 3 red
8 3 pink
9 3 green
解釋
mask = df.groupby("COL1").COL2.transform(lambda x: x.eq("red").any())
如果 COL2 中組中的任何項目具有紅色,則掩碼為 True
0 True
1 True
2 True
3 False
4 False
5 False
6 False
7 True
8 True
9 True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.