![](/img/trans.png)
[英]Unexpected KeyError When Merging Two Multi-Index Dataframes in Pandas
[英]Pandas: KeyError when trying to merge two dataframes
我有兩個 Excel 工作表(主表和輸入),索引列相同,但列數不同(見下文)。 如果添加了新行(請參閱 ID 103-105)或已更新輸入 DF 中的項目(請參閱 ID 102),我想將輸入 DF 合並到主 DF 中。 其他列可以忽略。
數據框 1(主):
數據框 2(輸入):
目標(以黃色標記的更新單元格):
我正在使用以下腳本:
inputDf = pd.read_excel(inputFileName).set_index("ID")
masterDf = pd.read_excel(masterFileName).set_index("ID")
# Update existing rows
masterDf.update(inputDf)
# find out which ids are new
ids_of_new_rows = set(inputDf.index) - set(masterDf.index)
# get new rows that should be added to master
rows_to_add = masterDf.loc[ids_of_new_rows, inputDf.columns & masterDf.columns]
我能夠更新主 DF 並獲得ids_of_new_rows
。 輸出: {'CR103', 'CR104', 'CR105'}
但是,在嘗試獲取rows_to_add
,我總是收到以下錯誤:
KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: "None of [Index(['CR103', 'CR104', 'CR105'], dtype='object', name='ID')] are in the [index]"
有任何想法嗎?
錯誤來自這樣一個事實,即['CR103', 'CR104', 'CR105']
中沒有ID
為['CR103', 'CR104', 'CR105']
的masterDf
,但在inputDf
。 你正在嘗試做的可能是
rows_to_add = inputDf.loc[ids_of_new_rows, inputDf.columns & masterDf.columns]
inputDf = pd.read_excel(inputFileName).set_index("ID")
masterDf = pd.read_excel(masterFileName).set_index("ID")
# Update existing rows
masterDf.update(inputDf)
# Add new rows
masterDf = pd.concat((masterDf, inputDf.loc[inputDf.index.difference(masterDf.index), inputDf.columns & masterDf.columns]))
這里Index.difference用於獲取inputDf
中不存在於masterDf
的索引值。
這是實現下面描述的結果的正確腳本。 簡單的解決方案是更改 inputDF 和 masterDF ...
# Define DataFrame
inputDf = pd.read_excel(inputFileName).set_index("ID")
masterDf = pd.read_excel(masterFileName).set_index("ID")
# Update existing rows
masterDf.update(inputDf)
# find out which ids are new
ids_of_new_rows = set(inputDf.index) - set(masterDf.index)
# get new rows that should be added to master
rows_to_add = inputDf.loc[ids_of_new_rows, inputDf.columns & masterDf.columns]
# add new rows to existing master
df_result = pd.concat([masterDf, rows_to_add])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.