使用另一个电子表格中的值将文本添加到空电子表格单元格(使用 Python)

Add text to empty spreadsheet cells using values from another spreadsheet (using Python)

我想使用另一个电子表格(参考 Excel)向电子表格(主要 Excel)中的空单元格添加文本。当某个(唯一)字符串出现在 Main Excel 的 'Code' 列中时,我想使用另一个电子表格中的值填充同一行上的空单元格,并且这些值与相同的唯一性相关联字符串。

我的 'dictionary' 电子表格(参考 Excel):

Code Country Capital Language
AU Australia Canberra English
FR France Paris French
US USA DC English

我要填写的电子表格(主要Excel):

Country Capital Language Code
AU
FR
US

我可以编写什么 python 代码来将相应的值输入到 Main Excel 中同一行的代码中?例如,当 python 在 Main Excel 的代码栏中看到“AU”时,我希望 python 添加“澳大利亚”、“堪培拉”和“英语”(在那order) 到与“AU”在同一行的 Country、Capital 和 Language 列。

The Main Excel I want to fill in, and the Reference Excel

你可以使用pandas做你想做的事。

import pandas as pd


main = pd.read_excel('main.xlsx')
reference = pd.read_excel('reference.xlsx')

# Below are two methods to fill values in Main Excel
# with values from Reference Excel, you only need choose one

# 1. Using Series map
columns = ['Language', 'Country', 'Capital']
for column in columns:
    main[column] = main['Code'].map(reference.set_index('Code')[column])

# 2. Using Dataframe update
main = main.set_index('Code').update(reference.set_index('Code'))

# At last, write the filled main dataframe to new excel
main.to_excel('filled_main.xlsx')