簡體   English   中英

如果它們在列中具有相同的值並且其中至少一個包含另一列中的字符串,如何保留多行

[英]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

我搜索了多個線程,似乎無法弄清楚這一點。 任何幫助,將不勝感激。 假設我有以下數據集(為了這個問題,我已經簡化了它)

在此處輸入圖像描述

我想將所有在 COL1 中包含相同值的行組合在一起,然后在 COL2 中搜索那些特定行的字符串“red”。 如果該組中至少有一行包含“紅色”,那么我想保留所有這些行。 因此,對於這個數據集,output 應該如下所示:

在此處輸入圖像描述

任何幫助將不勝感激。 我在 python 工作。 謝謝!

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.

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