.concat()

Anonymous contributor's avatar
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 pandas Series or DataFrame objects. 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: If True, reset the index in the resulting DataFrame. The new axis will be labeled 0, …, n-1. The default value is False.
  • keys: Constructs a hierarchical index using the provided keys as the outermost level. The default value is None.
  • levels: Specific levels to use for constructing a MultiIndex if keys are provided. The default value is None.
  • names: Names for the levels generated in the hierarchical index. The default value is None.
  • verify_integrity: If True, checks whether the new concatenated axis contains duplicates. The default value is False.
  • sort: If True, sorts the resulting Series or Dataframe by the keys. The default value is False.
  • copy: If False, avoid copying data unnecessarily. The default value is True.

Note: Only the objs parameter is required; all other parameters are optional.

Example

The example below demonstrates the use of .concat() method:

import pandas as pd
df1 = 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 B
0 1 3
1 2 4
0 5 7
1 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:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python:Pandas on Codecademy