我是Pandas的新手,正在尝试在两个数据框之间进行左连接。我收到一个KeyError。有人可以发现我的错误吗?我以为我可能想念的东西很容易。谢谢!

import pandas as pd
import xlrd


remediation_file = pd.read_excel('C:\\Users\garyd\\Desktop\\remediation-workbook.xlsx')

exception_file = pd.read_excel('C:\\Users\garyd\\Desktop\\exception-finished-file.xlsx')


remediation_file['Concat ID-Resource'] = remediation_file['ID'] + remediation_file['Resource']

exception_file['Concat ID-Resource'] = exception_file['ID'] + exception_file['Resource']

indexed_remediation_file = remediation_file.set_index(['Concat ID-Resource'])

indexed_exception_file = exception_file.set_index(['Concat ID-Resource'])

# print(indexed_remediation_file)

# print(indexed_exception_file)


join_file = pd.merge(indexed_remediation_file, indexed_exception_file, on = 'Concat ID-Resource', how='left')

# print(join_file)

最佳答案

这些线

indexed_remediation_file = remediation_file.set_index(['Concat ID-Resource'])

indexed_exception_file = exception_file.set_index(['Concat ID-Resource'])


使联合列成为每个DataFrame的索引。因此,当您要合并时,而不是使用

on='Concat ID-Resource'


使用

left_index=True,
right_index=True

关于python - 合并时的Pandas KeyError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50193368/

10-12 21:43