python - 来自不同列的 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]
解决方案
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]
从上面的代码分析:
基本上,您正在比较 excel-1 的 row1 和 excel-2 的 row-1 并匹配子字符串和字符串并获得主要和次要原因正确吗?
在这里,您将覆盖相同的位置,即 o/p 位置,因此,您始终只能得到 1 个结果。
问题在以下代码中:
df['Primary Reason']= df1['Primary Reason'][index]
df['Secondary Reason']=df1['Secondary Reason'][index]
提出逻辑,您可以将结果添加到与以下格式相同的行中
res1, res2 ....等
推荐阅读
- python - 从列表中删除特定元素并创建新的嵌套列表
- asp.net - 如何翻译 ASP.NET Core 中的默认 ModelErrors?
- python - python venv:在 Win 笔记本电脑中,我需要创建一个 venv 目录,然后将该目录 ftp 到 redhat
- php - 尝试通过 .htaccess 更新 PHP 版本
- go - 如何撤消“go mod init”
- amazon-web-services - 如何确认我的 AWS Lambda 函数更新成功?
- php - Python 到前端的通信
- oracle - 如何调用正在运行的 SQL 脚本的文件名?
- spring-boot - 主复合键 ID 上的 org.hibernate.NonUniqueObjectException
- string - Z3py 模型返回 EMPTY