1

我是 Pandas 的初学者,我想知道如何为我想执行的以下逻辑操作编写代码。

有人可以让我知道他们会怎么做吗?

如果单词在熊猫系列中,则从 DataFrame 中的字符串中删除该单词。

让“A”系列成为熊猫系列,如下所示:

index             word
0                 foo
1                 bar
2                 baz

让 DataFrame "B" 成为我们想要修改的 DataFrame。

index    string
0        foo bar hello there
1        foo Lax
2        bar Kay
3        John Smith

期望的输出:

0 hello there
1 Lax
2 Kay
3 John Smith
4

2 回答 2

4

让我们尝试使用.str.replace通过 using 创建的正则表达式join

s = pd.Series(['foo','bar','baz'])

df = pd.DataFrame({'string':['foo bar hello there', 'foo Lax', 'bar Kay', 'John Smith']})

df['string'].str.replace('|'.join(s), '')

输出:

0      hello there
1              Lax
2              Kay
3       John Smith
Name: string, dtype: object
于 2020-05-19T17:13:27.113 回答
0

这将删除剩余的前导空格:

df['string'].str.replace('|'.join(s), '').str.lstrip()
于 2020-05-19T18:01:10.007 回答