The Wayback Machine - https://web.archive.org/web/20240531095820/https://www.geeksforgeeks.org/how-to-merge-multiple-csv-files-into-a-single-pandas-dataframe/
Open In App

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

Last Updated : 09 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

While working with CSV files during data analysis, we often have to deal with large datasets. Sometimes, it might be possible that a single CSV file doesn’t consist of all the data that you need. In such cases, there’s a need to merge these files into a single data frame. Luckily, the Pandas library provides us with various methods such as merge, concat, and join to make this possible. Through the examples given below, we will learn how to combine CSV files using Pandas.

File Used:

First CSV – 

Second CSV – 

Third CSV – 

Method 1: Merging by Names

Let us first understand each method used in the program given above:

  • pd.concat(): This method stitches the provided datasets either along the row or column axis. It takes the dataframe objects as parameters. Along with that, it can also take other parameters such as axis, ignore_index, etc.
  • map(function, iterable): It executes a specified function for each item in iterables. In the example above, the pd.read_csv() function is applied to all the CSV files in the list given.

Approach:

  • At first, we import Pandas.
  • Using pd.read_csv() (the function), the map function reads all the CSV files (the iterables)  that we have passed. Now, pd.concat() takes these mapped CSV files as an argument and stitches them together along the row axis (default).  We can pass axis=1 if we wish to merge them horizontally along the column. Further,  ignore_index = True sets continuous index values for the merged dataframe.
  • The images are given below show mydata.csv, mydata1.csv, and the merged dataframe.

Example:

Python3




# importing pandas
import pandas as pd
  
# merging two csv files
df = pd.concat(
    map(pd.read_csv, ['mydata.csv', 'mydata1.csv']), ignore_index=True)
print(df)


Output:

Method 2: Merging All

Approach:

  • os.path.join() takes the file path as the first parameter and the path components to be joined as the second parameter. “mydata*.csv helps to return every file in the home directory that starts with “mydata” and ends with .CSV (Use of wildcard *).
  • glob.glob() takes these joined file names and returns a list of all these files. In this example, mydata.csv, mydata1.csv, and mydata2.csv are returned.
  • Now, just like the previous example, this list of files is mapped and then concatenated.

We can simply write these three lines of code as:

df = pd.concat(map(pd.read_csv, glob.glob(os.path.join(“/home”, “mydata*.csv”))), ignore_index= True)

Example:

Python3




# importing libraries
import pandas as pd
import glob
import os
  
# merging the files
joined_files = os.path.join("/home", "mydata*.csv")
  
# A list of all joined files is returned
joined_list = glob.glob(joined_files)
  
# Finally, the files are joined
df = pd.concat(map(pd.read_csv, joined_list), ignore_index=True)
print(df)


Output:



Similar Reads

How to merge multiple excel files into a single files with Python ?
Normally, we're working with Excel files, and we surely have come across a scenario where we need to merge multiple Excel files into one. The traditional method has always been using a VBA code inside excel which does the job but is a multi-step process and is not so easy to understand. Another method is manually copying long Excel files into one w
4 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Copying Csv Data Into Csv Files Using Python
CSV files, the stalwarts of information exchange, can be effortlessly harnessed to extract specific data or merge insights from multiple files. In this article, we unveil five robust approaches, transforming you into a virtuoso of CSV data migration in Python. Empower your data-wrangling endeavors, mastering the art of copying and organizing inform
4 min read
How to merge two csv files by specific column using Pandas in Python?
In this article, we are going to discuss how to merge two CSV files there is a function in pandas library pandas.merge(). Merging means nothing but combining two datasets together into one based on common attributes or column. Syntax: pandas.merge() Parameters : data1, data2: Dataframes used for merging.how: {‘left’, ‘right’, ‘outer’, ‘inner’}, def
3 min read
Combine Multiple Excel Worksheets Into a Single Pandas Dataframe
Prerequisites: Working with excel files using Pandas In these articles, we will discuss how to Import multiple excel sheet into a single DataFrame and save into a new excel file. Let's suppose we have two Excel files with the same structure (Excel_1.xlsx, Excel_2.xlsx), then merge both of the sheets into a new Excel file. Approach : Import-ModuleRe
1 min read
Pandas - Plot multiple time series DataFrame into a single plot
In this article, we are going to see how to plot multiple time series Dataframe into single plot. If there are multiple time series in a single DataFrame, you can still use the plot() method to plot a line chart of all the time series. To Plot multiple time series into a single plot first of all we have to ensure that indexes of all the DataFrames
4 min read
Read multiple CSV files into separate DataFrames in Python
Sometimes you might need to read multiple CSV files into separate Pandas DataFrames. Importing CSV files into DataFrames helps you work on the data using Python functionalities for data analysis. In this article, we will see how to read multiple CSV files into separate DataFrames. For reading only one CSV file, we can use pd.read_csv() function of
2 min read
Split single column into multiple columns in PySpark DataFrame
pyspark.sql.functions provide a function split() which is used to split DataFrame string Column into multiple columns. Syntax: pyspark.sql.functions.split(str, pattern, limit=- 1) Parameters: str: str is a Column or str to split.pattern: It is a str parameter, a string that represents a regular expression. This should be a Java regular expression.l
4 min read
Creating a dataframe using CSV files
CSV files are the “comma-separated values”, these values are separated by commas, this file can be viewed like an excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can get in CSV file format. Creating a pandas data frame using CSV files can
2 min read
How to read multiple data files into Pandas?
In this article, we are going to see how to read multiple data files into pandas, data files are of multiple types, here are a few ways to read multiple files by using the pandas package in python. The demonstrative files can be download from here Method 1: Reading CSV files If our data files are in CSV format then the read_csv() method must be use
3 min read
Article Tags :
Practice Tags :