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.

Table of contents

## 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"])`

returns

`A 42`

`B 30`

`C 59`

`D 7`

Checking the type

`type(s)`

returns

`<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()`

gives

`0`

`A 42`

`B 30`

`C 59`

`D 7`

Now, if we check the type:

`type(df)`

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`

## References

Links | Site |
---|---|

pandas.Series.to_frame | pandas.pydata.org |

pandas.Series | pandas.pydata.org |

Series | pandas.pydata.org |