How to convert a series to a dataframe with pandas

September 01, 2021    /    Viewed: 145    /    Comments: 0    /    Edit


Example of how to convert a series to a dataframe with pandas

Create a series with pandas

Let's create a dataframe with pandas:

    import pandas as pd
import numpy as np

data = np.random.randint(5, size=(5,))

s = pd.Series(data, index=["A", "B", "C", "D", "E"])

returns for example

A    4
B    4
C    0
D    1
E    0

To check if it is a series, just do:

type(s)

should return

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

Convert a series to a dataframe

To convert a series to a dataframe, a solution is to use pandas.Series.to_frame

df = s.to_frame()

gives

   0
A  4
B  4
C  0
D  1
E  0

Now, if we check the type:

type(df)

it should 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  E
0  4  4  0  1  0

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!