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

Example of how to convert a series to a dataframe 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'>`

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`

License

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.