In this post, we will see how to convert Pandas Series to DataFrame.
Table of Contents
series.to_frame()
method to convert Pandas Series to DataFrame.to_frame()
returns DataFrame representation of the series.
1 2 3 |
series.to_frame(self, name=None) |
Here,
name:
It is subsitute for series name, it will be None
if not provided.
Convert series to dataframe
You can convert Series to DataFrame using series.to_frame()
method.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 |
# import pandas library import pandas as pd # Creating the Series sr = pd.Series([100, 84, 92, 45, 65]) # convert series to dataframe using to_frame df = sr.to_frame() print(df) |
Output:
1 2 3 4 5 6 7 8 |
0 0 100 1 84 2 92 3 45 4 65 |
Convert Series to DataFrame with column name
You can convert Series to DataFrame using series.to_frame()
method and pass name parameter to label column.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 |
# import pandas library import pandas as pd # Creating the Series sr = pd.Series([100, 84, 92, 45, 65]) # convert series to dataframe using to_frame marks_df = sr.to_frame(name = 'Marks') print(marks_df) |
Output:
1 2 3 4 5 6 7 8 |
Marks 0 100 1 84 2 92 3 45 4 65 |
Pandas series to dataframe with index of Series as columns
Let’s say you have series and you want to convert index of series to columns in DataFrame.
1 2 3 |
series = pd.Series({'X': 'One', 'Y': 'Two', 'Z': 'Three'}) |
and you want output as
1 2 3 4 |
X Y Z 0 One Two Three |
In this scenario, you can convert the series to DataFrame and call transpose()
on the DataFrame to achieve these results.
Let’s see with help of example:
1 2 3 4 5 6 7 8 9 |
import pandas as pd series = pd.Series({'X': 'One', 'Y': 'Two', 'Z': 'Three'}) print("-------Series-------\n",series) df = pd.DataFrame(series) #Call transpose df = df.transpose() print("-------DataFrame-------\n",df) |
Output:
1 2 3 4 5 6 7 8 9 10 |
-------Series------- X One Y Two Z Three dtype: object -------DataFrame------- X Y Z 0 One Two Three |
Pandas series to DataFrame columns
If you want to convert series to DataFrame columns, then you can pass columns=series
.
Here is an example:
1 2 3 4 5 6 7 |
import pandas as pd series = pd.Series(['Name','Age','Gender']) print("-------Series-------\n",series) df = pd.DataFrame(columns=series) print("-------DataFrame-------\n",df) |
Output:
1 2 3 4 5 6 7 8 9 10 11 |
-------Series------- 0 Name 1 Age 2 Gender dtype: object -------DataFrame------- Empty DataFrame Columns: [Name, Age, Gender] Index: [] |
As you can see, series(Name, Age and Gender)
became columns for DataFrame.
That’s all about How to convert Pandas Series to DataFrame.