python - 根据条件创建并填充 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”填充所有行。
有正确的方法吗?
解决方案
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
。
推荐阅读
- amazon-web-services - 登录堡垒主机后无法 ping 和 ssh 登录到 ec2 实例
- reactjs - 如何通过服务器端的值在 useEffect 中设置状态
- flutter - Flutter:从 appbar 调用 listview builder 中的方法
- android - Android 11 (API30) 以编程方式设置“所有文件”权限
- java - 输入日期大于给定日期值
- python - 将 df 保存为 {index - list of all values} dict 格式
- git - Git恢复撤消的更改?
- matlab - Cayley-Hamilton 定理的系数
- python - NameError: name 'open' is not defined 尝试登录文件时
- python - 错误:在字符串格式化期间并非所有参数都转换了