首页 > 解决方案 > 根据列表数据比较将数据框与列表进行比较并更新数据框

问题描述

我正在尝试将数据框列中的文本与现有列表进行比较,然后根据比较更新数据框中的新列。数据框列中的文本比列表中的更复杂。如果数据框文本包含列表中的文本,我希望获取列表值并更新新的数据框列。我为此尝试了一个 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

标签: pandaslistdataframetextstring-comparison

解决方案


这里有两个实现,第一个遵循你的想法,第二个优化只使用一个 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

推荐阅读