How to Merge multiple CSV Files into a single Pandas dataframe ?



To merge more than one CSV files into a single Pandas dataframe, use read_csv. At first, import the required Pandas library. Here. We have set pd as an alias βˆ’

import pandas as pd

Now, let’s say the following are our CSV Files βˆ’

Sales1.csv

Sales2.csv

We have set the path as string. Both the files are on the Desktop βˆ’

file1 = "C:\Users\amit_\Desktop\sales1.csv"
file2 = "C:\Users\amit_\Desktop\sales2.csv"

Next, merge the above two CSV files. The pd.concat() merge the CSV files together βˆ’

dataFrame = pd.concat(
   map(pd.read_csv, [file1, file2]), ignore_index=True)

Example

Following is the code βˆ’

import pandas as pd

file1 = "C:\Users\amit_\Desktop\sales1.csv"
file2 = "C:\Users\amit_\Desktop\sales2.csv"

print("Merging multiple CSV files...")

# merge
dataFrame = pd.concat(
   map(pd.read_csv, [file1, file2]), ignore_index=True)
print(dataFrame)

Output

This will produce the following output βˆ’

          Car       Place   UnitsSold
0        Audi   Bangalore          80
1     Porsche      Mumbai         110
2  RollsRoyce        Pune         100
3         BMW       Delhi          95
4    Mercedes   Hyderabad          80
5  Lamborgini  Chandigarh          80
Updated on: 2021-09-27T11:11:57+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements