【问题标题】:Python - Search and present strings within a column in dataframe from a listPython - 从列表中搜索并显示数据框中的列中的字符串
【发布时间】:2020-03-16 06:33:21
【问题描述】:

我如何在 Python 中将从给定单词列表中找到的单词呈现在每一行的文本列中。

如果在文本列中找到多个单词,我想用“,”分隔它们。

示例:

我有以下清单:

color_list = ['White','Yellow','Blue','Red']

我需要在数据框 (df) 中搜索:

      doc    text             
0    3000 'colors White Yellow'
1    3001 'Green Black'
2    3002 'I want the color Red'

并将匹配的行插入到包含列表中匹配单词的新列中:

 doc      text                      words
0    3000 'colors White Yellow'    'White, Yellow'
1    3001 'Green Black'             
2    3002 'I want the color Red'   'Red'

我使用代码来提取匹配的单词,但我设法为每一行显示一个单词:

df['words'] = df.text.str.extract('(?i)({0})'.format('|'.join(color_list )))

我不知道如何在 Python 中做到这一点(在 R 中我做到了)

这个特定的问题是新的,因为挑战是展示更多 不是列表中的一个字符串,而不仅仅是一个值。

提前感谢您的帮助。

【问题讨论】:

  • 这个特定问题是新问题,因为挑战是从列表中显示多个字符串,而不仅仅是一个值。

标签: python regex pandas dataframe text


【解决方案1】:

你需要提取带有str.findall的单词,然后用", ".join加入结果:

import pandas as pd

color_list = ['White','Yellow','Blue','Red']
df = pd.DataFrame({"doc": [3000, 3001, 3002], "text": ["colors White Yellow", "Green Black", "I want the color Red"]})
df['words'] = df['text'].str.findall(r'(?i)\b(?:{})\b'.format('|'.join(color_list))).apply(', '.join)

输出:

    doc                  text          words
0  3000   colors White Yellow  White, Yellow
1  3001           Green Black               
2  3002  I want the color Red            Red

这假定color_list 中的所有术语仅包含单词字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2017-07-27
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    相关资源
    最近更新 更多