How to Merge Two or More Series in Pandas (With Examples)


You can use the following syntax to quickly merge two or more series together into a single pandas DataFrame:

df = pd.concat([series1, series2, ...], axis=1)

The following examples show how to use this syntax in practice.

Example 1: Merge Two Series in Pandas

The following code shows how to merge together two pandas Series into a single pandas DataFrame:

import pandas as pd

#define series
series1 = pd.Series(['Mavs', 'Rockets', 'Spurs'], name='Team')
series2 = pd.Series([109, 103, 98], name='Points')

#merge series into DataFrame
df = pd.concat([series1, series2], axis=1)

#view DataFrame
df

        Team	Points
0	Mavs	109
1	Rockets	103
2	Spurs	98

Note that if one series is longer than the other, pandas will automatically provide NaN values for missing values in the resulting DataFrame:

import pandas as pd

#define series
series1 = pd.Series(['Mavs', 'Rockets', 'Spurs'], name='Team')
series2 = pd.Series([109, 103], name='Points')

#merge series into DataFrame
df = pd.concat([series1, series2], axis=1)

#view DataFrame
df

        Team	Points
0	Mavs	109
1	Rockets	103
2	Spurs	NaN

Example 2: Merge Multiple Series in Pandas

The following code shows how to merge multiple series into a single pandas DataFrame:

import pandas as pd

#define series
series1 = pd.Series(['Mavs', 'Rockets', 'Spurs'], name='Team')
series2 = pd.Series([109, 103, 98], name='Points')
series3 = pd.Series([22, 18, 15], name='Assists')
series4 = pd.Series([30, 35, 28], name='Rebounds')

#merge series into DataFrame
df = pd.concat([series1, series2, series3, series4], axis=1)

#view DataFrame
df

	Team	Points	Assists	Rebounds
0	Mavs	109	22	30
1	Rockets	103	18	35
2	Spurs	98	15	28

Additional Resources

How to Merge Two Pandas DataFrames on Index
How to Merge Pandas DataFrames on Multiple Columns
How to Stack Multiple Pandas DataFrames

Leave a Reply

Your email address will not be published.