Table of Contents
Pandas offers the ability to combine two or more series into one. This can be done by using the pd.concat() function to concatenate multiple series into one. The syntax for this is simple: pd.concat([series_1, series_2, …, series_n], axis=1). The axis argument defines if the series should be combined along the columns (axis=1) or along the indices (axis=0). Once the series have been concatenated, the index and column labels will be kept and matched to the appropriate values in the merged series. Examples of merging two or more series can be found in the official Pandas documentation.
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