The Wayback Machine - https://web.archive.org/web/20240729161526/https://www.geeksforgeeks.org/pandas-concat-function-in-python/
Open In App

pandas.concat() function in Python

Last Updated : 01 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

The pandas.concat() function does all the heavy lifting of performing concatenation operations along with an axis of Pandas objects while performing optional set logic (union or intersection) of the indexes (if any) on the other axes.

Pandas concat() function Syntax

Syntax: concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy)

Parameters:

  • objs: Series or DataFrame objects
  • axis: axis to concatenate along; default = 0
  • join: way to handle indexes on other axis; default = ‘outer’
  • ignore_index: if True, do not use the index values along the concatenation axis; default = False
  • keys: sequence to add an identifier to the result indexes; default = None
  • levels: specific levels (unique values) to use for constructing a MultiIndex; default = None
  • names: names for the levels in the resulting hierarchical index; default = None
  • verify_integrity: check whether the new concatenated axis contains duplicates; default = False
  • sort: sort non-concatenation axis if it is not already aligned when join is ‘outer’; default = False
  • copy: if False, do not copy data unnecessarily; default = True

Returns: type of objs (Series of DataFrame)

Concatenate Using Pandas with Examples

Example 1: Concatenate DataFrames in Python

In this example, we are concatenating two series with default parameters in Pandas.

Python3




# importing the module
import pandas as pd
 
# creating the Series
series1 = pd.Series([1, 2, 3])
display('series1:', series1)
series2 = pd.Series(['A', 'B', 'C'])
display('series2:', series2)
 
# concatenating
display('After concatenating:')
display(pd.concat([series1, series2]))


Output

Pandas concat() function

Example 2: Pandas combining two dataframes horizontally with index = 1

In this example, we create two Pandas Series (series1 and series2), and then concatenates them along the columns (axis=1) using pd.concat(). The resulting DataFrame contains both Series as columns, creating a new DataFrame with two columns.

Python3




# importing the module
import pandas as pd
 
# creating the Series
series1 = pd.Series([1, 2, 3])
display('series1:', series1)
series2 = pd.Series(['A', 'B', 'C'])
display('series2:', series2)
 
# concatenating
display('After concatenating:')
display(pd.concat([series1, series2],
                  axis = 1))


Output

Pandas concat() function

Example 3: Concatenating 2 DataFrames and Assigning Keys

creates two DataFrames (df1 and df2), and concatenates them along with keys assigned to each DataFrame using pd.concat(). The resulting DataFrame has a hierarchical index with keys ‘key1’ and ‘key2’, distinguishing the origin of each set of data.

Python3




# importing the module
import pandas as pd
 
# creating the DataFrames
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                    'B': ['B0', 'B1', 'B2', 'B3']})
display('df1:', df1)
df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
                    'B': ['B4', 'B5', 'B6', 'B7']})
display('df2:', df2)
 
# concatenating
display('After concatenating:')
display(pd.concat([df1, df2],
                  keys=['key1', 'key2']))


Output

Pandas concat() function

Example 4: Concatenating DataFrames horizontally in Pandas with axis = 1

creates two DataFrames (df1 and df2), and concatenates them along the columns (axis=1) using pd.concat(). The resulting DataFrame combines columns from both df1 and df2, aligning them side by side.

Python3




# importing the module
import pandas as pd
 
# creating the DataFrames
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                    'B': ['B0', 'B1', 'B2', 'B3']})
display('df1:', df1)
df2 = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
                    'D': ['D0', 'D1', 'D2', 'D3']})
display('df2:', df2)
 
# concatenating
display('After concatenating:')
display(pd.concat([df1, df2],
                  axis = 1))


Output

Pandas concat() function

Example 5: Concatenating 2 DataFrames with ignore_index = True

creates two DataFrames (df1 and df2) with identical columns, and concatenates them vertically using pd.concat() with ignore_index=True. The resulting DataFrame has a continuous index, ignoring the original indices of df1 and df2.

Python3




# importing the module
import pandas as pd
 
# creating the DataFrames
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                    'B': ['B0', 'B1', 'B2', 'B3']})
display('df1:', df1)
df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
                    'B': ['B4', 'B5', 'B6', 'B7']})
display('df2:', df2)
 
# concatenating
display('After concatenating:')
display(pd.concat([df1, df2],
                  ignore_index = True))


Output

Pandas concat() function

Example 6: Concatenating a DataFrame with a Series

creates a DataFrame (df) and a Series (series), then concatenates them along the columns (axis=1) using pd.concat(). The resulting DataFrame combines the columns from df and the Series, aligning them side by side. Note: There’s a typo in the display statement (df1 instead of df).

Python3




# importing the module
import pandas as pd
 
# creating the DataFrame
df = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                    'B': ['B0', 'B1', 'B2', 'B3']})
display('df:', df1)
# creating the Series
series = pd.Series([1, 2, 3, 4])
display('series:', series)
 
# concatenating
display('After concatenating:')
display(pd.concat([df, series],
                  axis = 1))


Output

Pandas concat() function



Previous Article
Next Article

Similar Reads

How to Union Pandas DataFrames using Concat?
concat() function does all of the heavy liftings of performing concatenation operations along an axis while performing optional set logic (union or intersection) of the indexes (if any) on the other axes. The concat() function combines data frames in one of two ways: Stacked: Axis = 0 (This is the default option). Side by Side: Axis = 1 Steps to Un
1 min read
Python - tensorflow.concat()
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. concat() is used to concatenate tensors along one dimension. Syntax: tensorflow.concat( values, axis, name ) Parameter: values: It is a tensor or list of tensor.axis: It is 0-D tensor which represents dimension to concat
2 min read
Python Pandas - pandas.api.types.is_file_like() Function
In this article, we will be looking toward the functionality of pandas.api.types.is_file_like() from the pandas.api.types module with its various examples in the Python language. An object must be an iterator AND have a read or write method as an attribute to be called file-like. It is important to note that file-like objects must be iterable, but
2 min read
Python | pandas.to_markdown() in Pandas
With the help of pandas.to_markdown() method, we can get the markdown table from the given dataframes by using pandas.to_markdown() method. Syntax : pandas.to_markdown() Return : Return the markdown table. Example #1 : In this example we can see that by using pandas.to_markdown() method, we are able to get the markdown table from the given datafram
1 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Pandas Series dt.day_name() Method | Get Day From Date in Pandas
Pandas dt.day_name() method returns the day names of the DateTime Series objects with specified locale. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) resu
2 min read
Pandas Series dt.weekday | Find Day of the Week in Pandas
The dt.weekday attribute returns the day of the week. It is assumed the week starts on Monday, which is denoted by 0, and ends on Sunday which is denoted by 6. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day
2 min read
three90RightbarBannerImg