【问题标题】:How can you compare two excel workbooks in python?如何在 python 中比较两个 excel 工作簿?
【发布时间】:2020-06-28 06:37:13
【问题描述】:

我有一个 excel 工作簿 - sheet1 的值:

Names
--------
Aaron  |
Bob    |
Carl   |
Daron  |
Elle   |

我有另一个 excel 工作簿 - sheet2 的值:

Names       Marks
-------------------
Aaron    |   90
Bob      |   89

我希望使用 python 将缺失的名称附加到 sheet2 的工作簿 2 中,并在“标记”列中添加“无标记”。

有人可以帮忙吗?

提前谢谢你

【问题讨论】:

  • 是 2 个工作簿还是 1 个带 2 张工作簿的工作簿? A 列中的名称范围是多少?你有任何代码要发布吗?
  • 是的,它是 2 个工作簿
  • 我问的其他 2 个问题的答案是什么?

标签: python excel comparison missing-data


【解决方案1】:

试试这个

import pandas as pd

df_list_1 = pd.read_excel (r'data\excel\excel_1.xlsx', sheet_name='Sheet1') # Excel with names
df_list_2 = pd.read_excel (r'data\excel\excel_2.xlsx', sheet_name='Sheet1') # Excel with names and marks

df_list_1 = df_list_1.reset_index()
df_list_2 = df_list_2.reset_index()

df_diff = df_list_1[~df_list_1['Names'].isin(df_list_2['Names'])] # All names not in the second excel with the marks
df_diff = df_diff.fillna("No Marks") # Fill NA with 'no marks', marks on the second excel will be retained
df_list_final = df_list_2.append(df_diff) # Add all names that did not match
df_list_final = df_list_final.drop(['index'], axis=1).reset_index(drop=True) # Remove index column and reindex

print(df_list_final)

输出

     Names         A         B         C         D
0  Lambrie        90        85       NaN       NaN
1     Wade        70        50       NaN       NaN
2  Jurgens  No Marks  No Marks  No Marks  No Marks
3   Magdel  No Marks  No Marks  No Marks  No Marks
4     Liam        60        50        10        50

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多