[英]Remove substring from string if substring in list in data frame column
[英]Remove multi-word substring from string if substring in list in data frame column
在这里询问我的问题的后续问题: 如果 substring 在数据框列的列表中,则从字符串中删除 substring
我有以下数据框df1
string lists
0 I HAVE A PET DOG ['fox', 'pet dog', 'cat']
1 there is a cat ['dog', 'house', 'car']
2 hello EVERYONE ['hi', 'hello', 'everyone']
3 hi my name is Joe ['name', 'was', 'is Joe']
我正在尝试返回一个看起来像这样的数据框df2
string lists new_string
0 I HAVE A PET DOG ['fox', 'pet dog', 'cat'] I HAVE A
1 there is a cat ['dog', 'house', 'car'] there is a cat
2 hello everyone ['hi', 'hello', 'everyone']
3 hi my name is Joe ['name', 'was', 'is Joe'] hi my
我使用的解决方案不适用于 substring 是多个单词的情况,例如pet dog
or is Joe
df['new_string'] = df['string'].apply(lambda x: ' '.join([word for word in x.split() if word.lower() not in df['lists'][df['string'] == x].values[0]]))
这个问题大致相似,但仍然有很大不同。
在这种情况下,我们在行轴( axis=1
)上使用re.sub
:
df.apply(lambda row: re.sub("|".join(row["lists"]), "", row["string"], flags=re.I), axis=1)
string lists new_string
0 I HAVE A PET DOG [fox, pet dog, cat] I HAVE A
1 there is a cat [dog, house, car] there is a cat
2 hello EVERYONE [hi, hello, everyone]
3 hi my name is Joe [name, was, is Joe] hi my
分解它:
df.apply
with axis=1
将 function 应用于每一行re.sub
是str.replace
的正则表达式变体"|".join
来制作一个“|” 分隔字符串,在正则表达式中充当or
运算符。 所以它删除了这些词之一。flags=re.I
所以它忽略大小写字母。 注意:由于我们在行轴上使用apply
,这基本上是一个后台循环,因此不是很优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.