python - 如何检查列表和 DF 的记录之间是否匹配,并根据匹配的存在返回匹配的值
问题描述
我正在寻找测试以查看我的 DF 中的一个字段是否包含我定义的列表中也包含的年份。如果有匹配项,我想在我的数据框中标题为“年份”的新列中返回年份
我的输入:
#List of Years that I am scanning the data for
years = str((list(range(1970,2021))))
#Code to scan the field in my DF for a match and return the matching value if it exists. I am currently getting an error upon running this line.
string = posts['title']
for i in years:
posts['year'] = string.str.extract('(' + '|'.join(years) + ')')
总的来说,我希望我的输出如下所示
ID | 文本 | 年 |
---|---|---|
1234 | 我想要一辆 2004 年的法拉利 | 2004年 |
1235 | 我很想拥有一辆保时捷 | 钠 |
解决方案
你是在正确的方向,除了你不需要循环:
years = "|".join(map(str,range(1970,2021)) )
df['year'] = df.text.str.extract(f'({years})')
输出:
id text year
0 1234 i want a 2004 ferrari 2004
1 1235 i would love to have a porsche NaN
推荐阅读
- r - Geom_violinhalf 绘图侧
- python - 如何以图形方式将多列与单列 pandas 进行比较
- c# - 出现连接玩游戏但没有任何反应
- spring - 自动装配 CsvMapper
- java - 我们可以在 JAVA 中使用二进制文件写入和读取从文本文件中读取和写入多种类型的对象吗?
- visual-studio - 指定的 LocalDB 实例名称无效:能够创建迁移但不能运行它们
- javascript - 将 Zebra 浏览器打印绑定到 Vue 2.0
- python - 我怎样才能从较小的数量到最大的列表数量?
- kubernetes - 如何根据 GPU 指标扩展 Azure 的 Kubernetes 服务 (AKS)?
- javascript - 从日期字符串Javascript获取月份数