Concatenating CSV files using Pandas module
Using pandas we can perform various operations on CSV files such as appending, updating, concatenating, etc. In this article, we are going to concatenate two CSV files using pandas module.
Suppose we have one .csv file named Employee.csv which contains some records and it is as below:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
There is another .csv file named Updated.csv which contains new records as well as few records from Employee.csv file but with updated information. The file is given below:
We can see that the first five records in Updated.csv are new and the rest have updated information. For instance, the salaries of Louis and Diane are changed, email_id of Joe is different and so on.
The aim of this article is to add new records and update the information of existing records from Updated.csv file into Employee.csv.
Note: No two employees can have same emp_id.
Approach: Whenever it comes down to manipulate data using python we make use of Dataframes. The below approach has been used.
- Read Employee.csv and create a dataframe, say, employee_df..
- Similarly, read Updated.csv and from a dataframe, say, updated_df.
- Concatenate updated_df to employee_df and remove duplicates using emp_id as primary key.
- Create a new .csv file named Updated_Employees.csv containing all the old, new as well as updated records.
Below is the image of Updated_Employee.csv has been provided.
Below are the two CSV files which are going to be concatenated:
Now executing the below program to concatenate the above CSV files.
Below is the image of gfg3.csv: