5.3 C
London
Thursday, December 19, 2024
HomePandas in PythonGeneral Functions in PythonHow to Merge Two or More Series in Pandas (With Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories