【问题标题】:Removing specific words present in a numpy array from strings in a dataframe column? [Python]从数据框列中的字符串中删除 numpy 数组中存在的特定单词? [Python]
【发布时间】:2020-03-30 19:28:31
【问题描述】:

我有一个 numpy 单词数组,我想从 Pandas 数据框中的字符串中删除它们。 例如:如果该数组中有一个单词“the”,并且“The cat”列中有一个字符串。所以它应该变成'猫'。我不想删除整个字符串,只是那些单词。

# This will iterate that numpy array
def iterate():
    for x in range(0, 52):
        for y in range(0, 8):
              return (np_array[x,y])

# The code below drops that row/record

filtered = df[~df.content.str.contains(iterate())]

我们将不胜感激。

样本数据: numpy array = [a, about, and, across, after, after, in, on, as]

一个样品池: df['content'] = 今晚一定要收看唐纳德·特朗普和大卫·莱特曼的深夜节目!

示例输出: 一定要与大卫莱特曼一起观看唐纳德特朗普深夜,他今晚将展示前十名!

【问题讨论】:

  • 嗨!为了吸引人们帮助您,请分享示例数据,以便我们可以轻松地在本地计算机中重现问题。如果不弄脏手,大多数问题都无法解决。
  • @emremrah 谢谢,你现在可以看看。
  • 谢谢。首先,一旦 iterate 函数遇到 return 语句,函数就会停止,for 循环将不再迭代。我认为这不是您想要的行为。

标签: python pandas numpy data-science


【解决方案1】:

如果您能设法从该 Numpy 数组中获取要删除的停用词的平面列表,则可以构建一个匹配您要删除的所有停用词的正则表达式,然后使用 df.replace

stopwords = [
    "a", "about", "and", "across", "after",
    "afterwards", "in", "on", "as",
]

# Compile a regular expression that will match all the words in one sweep
stopword_re = re.compile("|".join(r"\b%s\b" % re.escape(word) for word in stopwords))

# Replace and reassign into the column
df["content"].replace(stopword_re, "", inplace=True)

如果您的应用程序需要,您还可以添加 .replace(re.compile(r"\s+"), " ") 将生成的多个空格合并为一个空格。

【讨论】:

  • 有些词仍然存在并且没有从字符串中删除,即使它们的频率已被删除。
  • 您的帮助将不胜感激。
  • 'the' 被删除,但 'The' 没有,我该如何处理?
  • , flags=re.I 添加到re.compile() 调用中,使其不区分大小写。
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 2014-02-26
  • 1970-01-01
  • 2018-10-25
相关资源
最近更新 更多