pandas - 根据列表数据比较将数据框与列表进行比较并更新数据框
问题描述
我正在尝试将数据框列中的文本与现有列表进行比较,然后根据比较更新数据框中的新列。数据框列中的文本比列表中的更复杂。如果数据框文本包含列表中的文本,我希望获取列表值并更新新的数据框列。我为此尝试了一个 for 循环,但我收到一个错误,即我的迭代器不是整数。以下是定义和我的代码。
myDF 是数据框 Product 是我要评估的列 makelist 是我要比较 myDF.Product 的字符串列表 如果匹配,我想更新 myDF.Brand。
当我运行以下命令时,我收到一条错误消息,指出我正在使用无效的变量类型进行索引。
import pandas as pd
myDF = pd.DataFrame({"Location": 'S1 S1 S1 S1 S1'.split(),
"Product": '12AB 34CD 56EF 78GH 90IJ'. split(),
"Brand": ""})
makelist = ['12A', '4CD', '56', '78G', '90IJ']
for items in myDF.Product:
for makes in makelist:
if makelist[makes] in(myDF.Product.iloc[items]):
myDF.Brand[items]=makelist[makes]
#expected output
Location Product Brand
0 S1 12AB 12A
1 S1 34CD 4CD
2 S1 56EF 56
3 S1 78GH 78G
4 S1 90IJ 90IJ
解决方案
这里有两个实现,第一个遵循你的想法,第二个优化只使用一个 for 循环。
设置
import pandas as pd
brands = ['12A', '4CD', '56', '78G', '90IJ']
两个 for 循环
myDF = pd.DataFrame({"Location": 'S1 S1 S1 S1 S1'.split(),
"Product": '12AB 34CD 56EF 78GH 90IJ'. split(),
"Brand": ""})
for product in myDF['Product']:
for brand in brands:
if brand in product:
myDF.loc[myDF['Product']==product, 'Brand'] = brand
myDF
Location Product Brand
0 S1 12AB 12A
1 S1 34CD 4CD
2 S1 56EF 56
3 S1 78GH 78G
4 S1 90IJ 90IJ
一个for循环
myDF = pd.DataFrame({"Location": 'S1 S1 S1 S1 S1'.split(),
"Product": '12AB 34CD 56EF 78GH 90IJ'. split(),
"Brand": ""})
for brand in brands:
myDF.loc[myDF['Product'].str.contains(brand), 'Brand'] = brand
myDF
Location Product Brand
0 S1 12AB 12A
1 S1 34CD 4CD
2 S1 56EF 56
3 S1 78GH 78G
4 S1 90IJ 90IJ
推荐阅读
- twitter - 超出速率限制,尝试访问“关注者”列表时出现代码 88
- python - 关于python中同一个键的多个值的问题
- python-3.x - 我如何让reportlab 在服务器上运行django?
- javascript - 获取 Array JavaScript 中最年轻和最年长的人
- python-3.x - 树视图图像不显示
- html - 如何将一个 div 类与不同的 CSS 图像样式属性配对
- android - 我正在从 Firebase 实时数据库中获取数据,但我得到空对象
- android - 亚行无法打开列出并允许添加账户的账户设置
- linux - Sed 删除文件夹内文件文本中的最后 4 个字符
- python - 无法从 node.js spawn 存储或发送 json 输出