首页 > 解决方案 > 来自不同列的 Python Pandas 字符串匹配

问题描述

我有一个 excel-1(原始数据)和 excel-2(参考文档)

在 excel-1 中,“评论”应与 excel-2“评论”列匹配。如果 excel-1“评论”列中的字符串包含 excel-2“评论”列中的任何子字符串,则主要原因和次要原因excel-2 的原因应针对 excel-1 中的每一行填充。

Excel-1 {'Item': {0: 'rr-1', 1: 'ss-2'}, 'Order': {0: 1, 1: 2}, 'Comments': {0: 'Good; Stock out of order,#1237-MF,Closing the stock ',1:'没有变化,坏,下周交货,09/12/2018-MF*'}}

Excel-2 {'评论':{0:'好',1:'缺货',2:'库存关闭',3:'没有变化',4:'坏库存',5:'下周交货'},'主要原因':{0:'质量',1:'仓库',2:'物流',3:'反馈',4:'仓库',5:'物流'},'次要原因':{0:'制造',1:'库存',2:'仓库',3:'反馈',4:'库存',5:'仓库'}}

请帮助建立逻辑。

当使用 pd.dataframe.str.contains/isin 函数进行单个匹配时,我得到了答案,但是如何编写逻辑来搜索多个匹配并以特定的结构格式编写。

想要的输出图片

for value in df['Comments']:
    string = re.sub(r'[?|$|.|!|,|;]',r'',value)
    for index,value in df1.iterrows():
        substring = df1.Comment[index]
        if substring in string:
            df['Primary Reason']= df1['Primary Reason'][index]
            df['Secondary Reason']=df1['Secondary Reason'][index]

标签: pythonexcelstringpandas

解决方案


df['Comments'] 中的值:

string = re.sub(r'[?|$|.|!|,|;]',r'',value)

for index,value in df1.iterrows():

    substring = df1.Comment[index]

    if substring in string:

        df['Primary Reason']= df1['Primary Reason'][index]

        df['Secondary Reason']=df1['Secondary Reason'][index]

从上面的代码分析:

  1. 基本上,您正在比较 excel-1 的 row1 和 excel-2 的 row-1 并匹配子字符串和字符串并获得主要和次要原因正确吗?

  2. 在这里,您将覆盖相同的位置,即 o/p 位置,因此,您始终只能得到 1 个结果。

问题在以下代码中:

df['Primary Reason']= df1['Primary Reason'][index]

df['Secondary Reason']=df1['Secondary Reason'][index]
  1. 提出逻辑,您可以将结果添加到与以下格式相同的行中

    res1, res2 ....等


推荐阅读