How to transform a series into a dataframe using pandas ?

Published: September 01, 2021

Updated: May 22, 2023

Tags: Python; Pandas; DataFrame; Protection Status

Pandas provides numerous useful tools to easily transform and manipulate data frames, including the ability to convert a series into a DataFrame. This tutorial will walk you through the process of transforming a series into a DataFrame using pandas.

Create a series with pandas

First, you'll need to import the necessary libraries. Start by importing pandas as pd:

import pandas as pd

Now that you have imported pandas, create your series object:

s = pd.Series([42, 30, 59, 7], index=["A", "B", "C", "D"])


A    42
B    30
C    59
D    7

Checking the type



<class 'pandas.core.series.Series'>

Convert a series to a dataframe

To convert this series into a DataFrame, use the to_frame() method. This returns a DataFrame object with column names as the data values from your Series:

df = s.to_frame()


A  42
B  30
C  59
D   7

Now, if we check the type:


it will return

<class 'pandas.core.frame.DataFrame'>

Note: if you want to swap rows and columns, a solution is to do:

df = df.T

returns here

    A   B   C  D
0  42  30  59  7


Links Site