Home > other >  Using Python Is there any way to copy data from one excel file to another excel file that has a diff
Using Python Is there any way to copy data from one excel file to another excel file that has a diff

Time:09-30

I am new to Python and stackoverflow. I am trying to do is copy data from 1 excel file to another excel file using pandas and numpy. Let's say,

first.csv contains

ID Title Country Status Date Region

1 Project1 US Active 09/29/20 America

2 Project2 Brazil Active America

3 Project3 China Active Asia

and second.csv contains

ID, Title, Country, Region, Date, Status, Description

1, Project1, US, America, N/A, Active, zzz,

4, Project4, Canada, America, N/A, Active, zzz,

5, Project5, Africa, Africa, N/A, Active, zzz,

In second file, the Column Status is after Date where as in first file it is after Country. I want to copy first.csv data to second.csv file based on the column structure of second.csv

After Copying I want my second.csv to look like

ID, Title, Country, Region, Date, Status, Description

1, Project1, US, America, N/A, Active, zzz,

2, Project2, Brazil , America, N/A, Active, zzzzzzz

3, Project3, China, Asia, N/A, Active, zzzzzzzzzzz

4, Project4, Canada, America, N/A, Active, zzz,

5, Project5, Africa, Africa, N/A, Active, zzz,

I was wondering if there is any way to merge/ copy the file in this way in Python using numpy and pandas library

CodePudding user response:

The pandas library makes this easy. Once you have both in memory as data frames, you can just append one to the other. The append will rearrange the columns to match the first df, and just keep empty any columns in csv1_df that aren't in csv2_df.

csv1_df = pd.read_csv('first.csv')
csv2_df = pd.read_csv('second.csv')
combined_df = csv2_df.append(csv1_df, ignore_index=True)
combined_df.to_csv('third.csv', header=True, mode='w')
  • Related