首页 > 解决方案 > 根据条件创建并填充 DataFrame 列

问题描述

我有一个 DataFrame,我需要创建一个新列并根据在文本中找到的单词列表中的单词数填充值。我正在尝试以下代码:

df = pd.DataFrame({'item': ['a1', 'a2', 'a3'], 
               'text': ['water, rainbow', 'blue, red, white','country,school,magic']})


list_of_words = ['water', 'pasta', 'black', 'magic', 'glasses', 'school' ,'book']

for index,row in df.iterrows():
    text = row['text']
        count_found_words = 0
        for word in list_of_words:
            found_words= re.findall(word, text)
            if len(found_words)>0:
                count_found_words += 1
        df['found_words'] = count_found_words

此代码实际上创建了一个新列,但使用循环的最后一个“count_found_words”填充所有行。

有正确的方法吗?

标签: pythonpandas

解决方案


pattern = fr"\b({'|'.join(list_of_words)})\b"

df["found_words"] = df.text.str.findall(pattern).str.len()

这形成了\b(water|pasta|black|magic|glasses|school|book)\b查找列表中任何单词的正则表达式。找到所有可能的并通过 报告匹配的数量.len


推荐阅读