Looking to merge two Excel files by ID into one Excel file using Python 2.7

前端 未结 1 1065
情深已故
情深已故 2020-12-21 23:55

I am new to the Python family and have been trying to solve merge two Excel files for days. I have researched merging endlessly and tried to adapt my code to fit my needs,

1条回答
  •  隐瞒了意图╮
    2020-12-22 00:25

    While we could fix your code, I'd strongly recommend looking into the pandas library if you're going to be doing this sort of work instead. It makes life a lot easier, and often borderline trivial.

    For example, if we had two csv files (although we could have started straight from Excel files if we wanted):

    >>> !cat scores3.csv
    ID,JanSales,FebSales
    1,100,200
    2,200,500
    3,300,400
    >>> !cat scores4.csv
    ID,CreditScore,EMMAScore
    2,good,Watson
    3,okay,Thompson
    4,not-so-good,NA
    

    We could read these into objects called DataFrames (think of them sort of like Excel sheets):

    >>> import pandas as pd
    >>> s3 = pd.read_csv("scores3.csv")
    >>> s4 = pd.read_csv("scores4.csv")
    >>> s3
       ID  JanSales  FebSales
    0   1       100       200
    1   2       200       500
    2   3       300       400
    >>> s4
       ID  CreditScore EMMAScore
    0   2         good    Watson
    1   3         okay  Thompson
    2   4  not-so-good       NaN
    

    And then we can merge them on the ID column:

    >>> merged = s3.merge(s4, on="ID", how="outer")
    >>> merged
       ID  JanSales  FebSales  CreditScore EMMAScore
    0   1       100       200          NaN       NaN
    1   2       200       500         good    Watson
    2   3       300       400         okay  Thompson
    3   4       NaN       NaN  not-so-good       NaN
    

    After which we could save it to a csv file or to an Excel file:

    >>> merged.to_csv("merged.csv")
    >>> merged.to_excel("merged.xlsx")
    

    0 讨论(0)
提交回复
热议问题