根据其他列值删除字符串中的单词

时间:2020-05-28 09:36:39

标签: python pandas string string-comparison

我有两列,它们是字符串格式的逗号分隔单词和单个单词的组合。 col1将始终只包含一个单词。在此示例中,我将使用单词 Dog 作为col1中的单词,但这在实际数据中会有所不同,因此请不要提出在“狗” 。

df = pd.DataFrame({"col1": ["Dog", "Dog", "Dog", "Dog"],
                     "col2": ["Cat, Mouse", "Dog", "Cat", "Dog, Mouse"]})

我想检查col1中的单词是否出现在col2的字符串中,如果确实出现,我想从col2中删除该单词。但是请记住,如果还有更多的单词,我想保留字符串的其余部分。所以它会从这里开始:

    col1    col2    
0   Dog     Cat, Mouse
1   Dog     Dog
2   Dog     Cat
3   Dog     Dog, Mouse

对此:

    col1    col2
0   Dog     Cat, Mouse
1   Dog 
2   Dog     Cat
3   Dog     Mouse

3 个答案:

答案 0 :(得分:2)

尝试一下:

import re
df['col2'] = [(re.sub(fr"({word}[\s,]*)","",sentence)) 
             for word,sentence in zip(df.col1,df.col2)]
df

    col1    col2
0   Dog     Cat, Mouse
1   Dog 
2   Dog     Cat
3   Dog     Mouse

另一个df,中间是狗:

df = pd.DataFrame({"col1": ["Dog", "Dog", "Dog", "Dog","Dog"],
                     "col2": ["Cat, Mouse", "Dog", "Cat", "Dog, Mouse", "Cat, Dog, Mouse"]})

df


   col1     col2
0   Dog     Cat, Mouse
1   Dog     Dog
2   Dog     Cat
3   Dog     Dog, Mouse
4   Dog     Cat, Dog, Mouse

应用上面的代码:

   col1     col2
0   Dog     Cat, Mouse
1   Dog 
2   Dog     Cat
3   Dog     Mouse
4   Dog     Cat, Mouse

答案 1 :(得分:1)

(^,|,$) 处理开头和结尾的逗号
(,\s|,) 将删除替换操作后保留的逗号。
{1,} 跳过不重复的逗号

df['col2'] = df['col2'].str. \
    replace("|".join(df['col1'].unique()), "").str.strip() \
    .str.replace("(?:^,|,$)", "") \
    .str.replace("(?:,\s|,){1,}", ",")

  col1          col2
0  Dog     Cat,Mouse
1  Dog              
2  Dog           Cat
3  Dog   Mouse,Mouse

答案 2 :(得分:1)

l=df.col1.tolist()#col1列表

col2创建集合,通过应用lambda函数查找差异来评估集合中l的成员资格。

df['col2']=list(zip(df.col2))
df['col2']=df.col2.apply(lambda x:[*{*x}-{*l}]).str[0]

enter image description here