首页 > 解决方案 > 如何比较从python中不同的excel文件中提取的两列

问题描述

我正在尝试提取两列,每列取自两个不同的 excel 文件,列的内容顺序不同,并且其中也有几个不同的项目,所以我试图检查一列的内容是否是存在于另一个中,如果存在,我想从另一列打印相应的值,这就是我迄今为止想出的

import pandas as pd
A = pd.read_excel('testcase_database.xlsx') #The excel file from which the data is to be taken
B = pd.read_excel('S32K3XX_SecureBAF_Sprint3_Test_Report.xlsx', sheet_name='Test_Report') #The excel file to which the data is to be updated
tcname = A['Unnamed: 2'] #Test case nams in A
fcname = B['Unnamed: 5'] #Test case names in B
pf = B['Unnamed: 15'] #Results in B
pi = A['Unnamed: 5'] #Results in A

temp = ""
temp1 = ""
#To compare the test case names in A and B and then printing that test case result in B
for i in tcname:
    temp = tcname[i]
    for j in fcname:
        temp1 = fcname[j]
        if temp==temp1:
            print(pf[j])
        else:
            continue

我收到一个关键错误,我做错了什么

标签: pythonexcelpandas

解决方案


它可能会抛出 a KeyErrortemp = tcname[i]因为for i in tcname:循环遍历您的 column 的值tcname。即i= some_row_value- 然后您不能将其用作tcname[i].

我没有你的意见,但这可能会达到同样的效果:

import pandas as pd
A = pd.read_excel('testcase_database.xlsx') #The excel file from which the data is to be taken
B = pd.read_excel('S32K3XX_SecureBAF_Sprint3_Test_Report.xlsx', sheet_name='Test_Report') #The excel file to which the data is to be updated
tcname = A['Unnamed: 2'] #Test case nams in A
fcname = B['Unnamed: 5'] #Test case names in B
pf = B['Unnamed: 15'] #Results in B
pi = A['Unnamed: 5'] #Results in A

for temp in tcname:
    for j, temp1 in enumerate(fcname):
        if temp == temp1:
            print(pf[j])
        else:
            continue

推荐阅读