来自不同列的Python Pandas字符串匹配

2024-05-15 17:04:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Excel-1 {'Item':{0:'rr-1',1:'ss-2'},'Order':{0:1,1:2},'Comments':{0:'好;缺货,#1237-MF,关闭库存',1:'没有变化,坏,下周交货,09/12/2018-MF*'}}

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

请帮助构建逻辑。在

我得到答案时,有一个单一的匹配使用pd.dataframe.str。包含/isin函数,但如何编写逻辑以搜索多个匹配项并以特定结构格式写入。在

desired output picture

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]

Tags: 字符串indfindexvalue库存原因excel
1条回答
网友
1楼 · 发布于 2024-05-15 17:04:13

对于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的行1和excel-2的行1,匹配子字符串和字符串,得到主次原因对吗?

  2. 在这里,重写同一个位置即o/p位置,因此,结果总是只有1个。

问题出现在以下代码中:

^{pr2}$
  1. 想出一个逻辑,在这个逻辑中,你可以把结果加在下面格式的同一行中

    res1,res2….等

相关问题 更多 >