Python:Pandas .concat()
Anonymous contributor
Published Jul 25, 2024
Contribute to Docs
The .concat() function is used to concatenate and combine multiple DataFrames or Series along a particular axis.
Syntax
pandas.concat(objs, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True)
objs: Denotes the objects to concatenate, which can be a sequence or mapping of pandasSeriesorDataFrameobjects. It must be specified and can be passed as a list, tuple, dictionary, Series, or DataFrame.axis: Specifies the axis to concatenate the objects. The default value is 0 for rows, while 1 represents columns.join: Determines how to handle indexes on other axes. Options include “outer” (default), “inner,” “left,” or “right.”ignore_index: IfTrue, reset the index in the resulting DataFrame. The new axis will be labeled 0, …, n-1. The default value isFalse.keys: Constructs a hierarchical index using the provided keys as the outermost level. The default value isNone.levels: Specific levels to use for constructing a MultiIndex if keys are provided. The default value isNone.names: Names for the levels generated in the hierarchical index. The default value isNone.verify_integrity: IfTrue, checks whether the new concatenated axis contains duplicates. The default value isFalse.sort: IfTrue, sorts the resultingSeriesorDataframeby the keys. The default value isFalse.copy: IfFalse, avoid copying data unnecessarily. The default value isTrue.
Note: Only the
objsparameter is required; all other parameters are optional.
Example
The example below demonstrates the use of .concat() method:
import pandas as pddf1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})result = pd.concat([df1, df2])print(result)
The example will result in a new DataFrame created by concatenating df1 and df2 along the rows. The output is as follows:
A B0 1 31 2 40 5 71 6 8
Codebyte Example
The code demonstrates the .concat() function on two DataFrames, concatenating df1 and df2 column-wise (axis=1) and using keys to create a hierarchical column index:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Pandas on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours