删除出现在其他列中的词,Pandas
怎么从一列的字符串中去掉另一列中出现的单词呢?
举个例子:
Sr A B C
1 jack jack and jill and jill
2 run you should run, you should ,
3 fly you shouldnt fly,there you shouldnt ,there
我想要的是 列C
,也就是 列B 减去 列A 的内容。请注意第三个例子,里面的 fly
后面跟着一个逗号,所以在处理的时候也要考虑到标点符号(如果代码是用来检测周围的空格的话)。
列A
里也可能有两个单词,所以这些也需要被去掉。
我需要在Pandas中写一个表达式,类似于:
df.apply(lambda x: x["C"].replace(r"\b"+x["A"]+r"\b", "").strip(), axis=1)
2 个回答
5
这个看起来怎么样?
In [24]: df
Out[24]:
Sr A B
0 1 jack jack and jill
1 2 run you should run,
2 3 fly you shouldnt fly,there
[3 rows x 3 columns]
In [25]: df.apply(lambda row: row.B.strip(row.A), axis=1)
Out[25]:
0 and jill
1 you should run,
2 ou shouldnt fly,there
dtype: object