Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.concat() Function

The Pandas concat() function

Pandas Universal Functions Common Pandas functions


pd.concat() is a function in the Pandas library used for **concatenating (joining) multiple Series or DataFrames**. It can merge multiple objects into a new one along rows or columns.

It is one of the most common merge operations in data processing, whether appending data vertically or merging fields horizontally,pd.concat() it can handle both.

Word meaning: concat is short for "concatenate", meaning to join multiple things end to end.


Basic syntax and parameters

pd.concat() is a top-level function of the Pandas library used to concatenate multiple Series or DataFrame objects along a specified axis.

Syntax format



pd.concat(objs, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False)

Parameter Description

- Type: Series, DataFrame, or a list of them. - Description: One or more Series/DataFrame objects to concatenate. Can be a single object, a list, or a dictionary. - Type: Integer (0 or 1). - Description: Specifies the axis along which to concatenate. `0` means concatenating by rows (vertical append), `1` means concatenating by columns (horizontal merge). The default is `0`. - Type: string ('outer' or 'inner'). - Description: How to handle indices that do not match along the concatenation axis. 'outer' means take the union (keep all indices), 'inner' means take the intersection (keep only common indices). Defaults to 'outer'. - Type: boolean. - Description> If 'True', the original indices are not used after concatenation; instead a new integer index is created. Defaults to 'False'. - Type> sequence. - Description: Used to create a multi-level index after concatenation, identifying the source of each original object. Defaults to 'None'.

Function description


Example

Let us thoroughly master pd.concat() through a series of examples from simple to complex.

Example 1: Basic usage - vertically concatenate Series

Example

import

pandas

as

pd

1. Create two Series

s1

=

pd.

Series

(

[

'Alice'

,

'Bob'

,

'Charlie'

]

,

name

=

'name'

)

s2

=

pd.

Series

(

[

'Diana'

,

'Eve'

,

'Frank'

]

,

name

=

'name'

)

print

(

"=== Original Series ==="

)

print

(

"s1:"

,

s1.

tolist

(

)

)

print

(

"s2:"

,

s2.

tolist

(

)

)

2. Use pd.concat() to concatenate vertically (default axis=0)

result

=

pd.

concat

(

[

s1

,

s2

]

)

print

(

"\n=== pd.concat([s1, s2]) vertical concatenation result ==="

)

print

(

result

)

3. Ignore the original indices and create a new integer index

result_ignore

=

pd.

concat

(

[

s1

,

s2

]

,

ignore_index

=

True

)

print

(

"\n=== ignore_index=True result ==="

)

print

(

result_ignore

)

Expected output:



=== 原始 Series ===

s1: ['Alice', 'Bob', 'Charlie']

s2: ['Diana', 'Eve', 'Frank']



=== pd.concat([s1, s2]) 纵向拼接结果 ===

0      Alice

1        Bob

2    Charlie

0     Diana

1        Eve

2     Frank

dtype: object



=== ignore_index=True 结果 ===

0      Alice

1        Bob

2    Charlie

3      Diana

4        Eve

5      Frank

dtype: object

Code analysis:

  1. pd.concat([s1, s2]) Concatenate two Series vertically into a longer Series.
  2. By default, the original indices are kept, so there will be duplicate index values 0, 1, 2.
  3. Settings ignore_index=True You can regenerate a consecutive numeric index.

Example 2: Horizontally concatenate DataFrame

Use axis=1 You can concatenate multiple DataFrames by column, which is useful when merging different fields.

Example

import

pandas

as

pd

1. Create two DataFrames

df1

=

pd.

DataFrame

(

{

   

'name'

:

[

'Alice'

,

'Bob'

,

'Charlie'

]

,

   

'age'

:

[

25

,

30

,

35

]

}

)

df2

=

pd.

DataFrame

(

{

   

'city'

:

[

'Beijing'

,

'Shanghai'

,

'Guangzhou'

]

,

   

'score'

:

[

85

,

90

,

95

]

}

)

print

(

"=== Original DataFrame ==="

)

print

(

"df1:"

)

print

(

df1

)

print

(

"\ndf2:"

)

print

(

df2

)

2. Concatenate horizontally (axis=1)

result

=

pd.

concat

(

[

df1

,

df2

]

,

axis

=

1

)

print

(

"\n=== pd.concat([df1, df2], axis=1) horizontal concatenation ==="

)

print

(

result

)

Expected output:



=== 原始 DataFrame ===

df1:

      name  age

0   Alice   25

1     Bob   30

2 Charlie   35



df2:

        city  score

0   Beijing     85

1  Shanghai     90

2  Guangzhou     95



=== pd.concat([df1, df2], axis=1) 横向拼接 ===

      name  age      city  score

0   Alice   25   Beijing     85

1     Bob   30  Shanghai     90

2 Charlie   35  Guangzhou     95

Code analysis:

Example 3: Use the keys parameter to create a hierarchical index

keys The parameter helps identify the data source, which is very useful when merging content from different datasets.

Example

import

pandas

as

pd

1. Create a dictionary containing multiple Series

data

=

{

   

'group_a'

: pd.

Series

(

[

1

,

2

,

3

,

4

]

)

,

   

'group_b'

: pd.

Series

(

[

5

,

6

,

7

,

8

]

)

,

   

'group_c'

: pd.

Series

(

[

9

,

10

,

11

,

12

]

)

}

print

(

"=== Concatenate using the keys parameter ==="

)

2. Use the keys parameter to create a hierarchical index

result

=

pd.

concat

(

data

,

keys

=

[

'Group 1'

,

'Group 2'

,

'third group'

]

)

print

(

result

)

3. Access data at a specific level

print

(

"\n=== Access data of 'first group' ==="

)

print

(

result

[

'Group 1'

]

)

Expected output:



=== 使用 keys 参数拼接 ===

第一组  group_a    1

        group_b    2

        group_c    3

        group_a    4

第二组  group_a    5

        group_b    6

        group_c    7

        group_a    8

第二组  group_b    9

...

Code analysis:

Example 4: Handling DataFrames with different columns (join parameter)

When the DataFrames to concatenate have different columns, you can use the join parameter to control how they are handled.

Example

import

pandas

as

pd

1. Create DataFrames with different columns

df1

=

pd.

DataFrame

(

{

   

'name'

:

[

'Alice'

,

'Bob'

]

,

   

'age'

:

[

25

,

30

]

}

)

df2

=

pd.

DataFrame

(

{

   

'name'

:

[

'Charlie'

,

'Diana'

]

,

   

'score'

:

[

85

,

90

]

}

)

print

(

"=== Original DataFrame ==="

)

print

(

"df1:"

)

print

(

df1

)

print

(

"\ndf2:"

)

print

(

df2

)

2. Outer join (default) - keep all columns

print

(

"\n=== join='outer' (outer join) ==="

)

print

(

pd.

concat

(

[

df1

,

df2

]

,

join

=

'outer'

)

)

3. Inner join - keep only common columns

print

(

"\n=== join='inner' (inner join) ==="

)

print

(

pd.

concat

(

[

df1

,

df2

]

,

join

=

'inner'

)

)

Expected output:



=== 原始 DataFrame ===

df1:

    name  age

0  Alice   25

1    Bob   30



df2:

      name  score

0  Charlie     85

1    Diana     90



=== join='outer' (外连接) ===

      name   age  score

0    Alice  25.0   NaN

1      Bob  30.0   NaN

0  Charlie  NaN  85.0

1   Diana  NaN  90.0



=== join='inner' (内连接) ===

      name

0    Alice

1      Bob

0  Charlie

1  Diana

Code analysis:


Tip: pd.concat() Suitable for simple concatenation. For more complex merges (such as matching based on column values), see pd.merge() function in Vue 3.

Pandas Common Functions Common Pandas functions