【问题标题】:Check if word is in a series, then delete it from a string检查单词是否在一个系列中,然后从字符串中删除它
【发布时间】:2020-05-19 17:04:11
【问题描述】:

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

有人可以告诉我他们会怎么做吗?

如果单词在 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

【问题讨论】:

  • A系列中的任何单词或与B系列相同索引对应的单词?

标签: python pandas jupyter-notebook data-munging data-wrangling


【解决方案1】:

让我们尝试使用.str.replace 和使用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

【讨论】:

  • 谢谢!很有趣,你能解释一下'|'是什么吗?和连接在这里做什么?
  • @jerof '|'.join(s) 从 s 创建这个字符串,“foo|bar|baz”,这是一个正则表达式,其中 |表示或。
  • 谢谢!很清楚,如果其中一个字符串是“foob barb”,你的方法会改变吗?我想要了解的是,当系列“s”中的单词是 df['string'] 中连贯短语/单词的一部分时会发生什么。然后输出将是“b b”,因为 foo 和 bar 将被替换为 ' '。您认为有办法防止这种情况发生吗?
  • 您可以将其添加到您的字符串或查找正则表达式替换。我认为“foo[b]?”是正确的正则表达式,但我需要测试。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2021-05-20
    • 2023-02-02
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 2021-09-23
    • 2016-05-08
    相关资源
    最近更新 更多