【问题标题】:Compare two excel sheets in Python using Pandas使用 Pandas 在 Python 中比较两个 Excel 工作表
【发布时间】:2020-07-01 09:34:39
【问题描述】:

我有两张 Excel 表格 - Sheet1 和 sheet2。将 sheet1 中的 A 列值与 sheet2 中的 A 列所有值进行比较。如果匹配,则将 sheet2 中匹配行的 C 列值复制到 sheet1 中的 C 列。

表 1

    Serial    Value
    123        
    345 
    567
    890
    120
    123
    345
    123
    890

表 2

    Serial   Value
    123      Name
    890      Class
    123      Name
    345      Division
    567      School
    123      Name

代码运行后,Sheet1 应该是:

    Serial     Value
    123        Name
    345        Division
    567        School
    890        Class
    120
    123        Name
    345        Division
    123        Name
    890        Class 

【问题讨论】:

  • 您的问题是什么?您是否尝试解决问题?为什么需要 pandas 来解决这个问题?
  • 是的,我用 Python 代码尝试过,但无法做到。需要帮助使用python代码解决它

标签: python pandas


【解决方案1】:

你可以使用 Pandas 的map 方法:

import pandas as pd

# your data
Sheet1 = pd.DataFrame({'Serial': [123, 345, 567, 890, 120, 123, 345, 123, 890]})
Sheet2 = pd.DataFrame({'Serial': [123, 890, 123, 345, 567, 123], 
                       'Value': ['Name', 'Class', 'Name', 'Division', 'School', 'Name']})

# transform Sheet2 into a dictionary that we can use as the mapping function
key = pd.Series(list(Sheet2['Value']), index=Sheet2['Serial']).to_dict()

# apply this mapping function to Sheet1
Sheet1['Value'] = Sheet1['Serial'].map(key)

# show results
display(Sheet1)

输出:

 Serial     Value
0   123     Name
1   345     Division
2   567     School
3   890     Class
4   120     NaN
5   123     Name
6   345     Division
7   123     Name
8   890     Class

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多