【问题标题】:String replace with multiple items字符串替换为多个项目
【发布时间】:2018-04-28 17:11:40
【问题描述】:

我有两个熊猫数据框。一个包含文本,另一个包含一组我想在文本中搜索和替换的术语。我创建了一个循环,它能够用一个术语替换文本中的每个单词,但是它非常慢,特别是考虑到它正在处理一个大型语料库。

我的问题是: 有没有更有效的解决方案可以复制我下面的方法?

示例文本数据框:

d = {'ID': [1, 2, 3], 'Text': ['here is some random text', 'random text here', 'more random text']}
text_df = pd.DataFrame(data=d)

示例术语数据框:

d = {'Replace_item': ['<RANDOM_REPLACED>', '<HERE_REPLACED>', '<SOME_REPLACED>'], 'Text': ['random', 'here', 'some']}
replace_terms_df = pd.DataFrame(data=d)

当前解决方案示例:

def find_replace(text, terms):
for _, row in terms.iterrows():
    term = row['Text']
    item = row['Replace_item']
    text.Text = text.Text.str.replace(term, item)
    return text
find_replace(text_df, replace_terms_df)

如果以上任何内容需要澄清,请告诉我。谢谢,

【问题讨论】:

  • 你能定义“非常相似的术语而不是精确的术语”吗?我的直觉这不是微不足道的,可能更好地作为一个单独的问题提出。
  • 好点 jpp。我将删除它并作为一个单独的问题提出。

标签: python pandas nlp


【解决方案1】:

在三列上使用zip + str.replace,并一次将结果分配给列,将时间减少了50%(使用%timeit,从~400us到~200us):

text_df['Text'] = [z.replace(x, y) for (x, y, z) in zip(replace_terms_df.Text, replace_terms_df.Replace_item, text_df.Text)]

【讨论】:

  • 谢谢阿米!我想知道是否有一种矢量化方法也可以提高性能?
  • 不客气,但我分享你的问题,是否有矢量化的方式来做到这一点(据我所知,没有)。
  • “terms”数据帧的长度是否总是必须等于或大于“text”数据帧的长度?我一直在进行一些测试,当术语比文本短时会遇到问题。
猜你喜欢
  • 2011-06-23
  • 2015-03-15
  • 1970-01-01
  • 2020-08-31
  • 2022-01-08
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
  • 2013-03-14
相关资源
最近更新 更多