Pandas to_frame()

The to_frame() method in Pandas is used to convert a Series to a DataFrame.

Example

import pandas as pd

# create a Series
series = pd.Series([1, 2, 3, 4, 5])

# convert the Series to a DataFrame dataframe = series.to_frame()
print(dataframe) ''' Output 0 1 1 2 2 3 3 4 4 5 '''

to_frame() Syntax

The syntax of the to_frame() method in Pandas is:

Series.to_frame(name=None)

to_frame() Arguments

The to_frame() method takes following argument:

  • name (optional) - allows us to provide a name for the column in the newly created DataFrame. If it's not specified, the Series name (if it exists) is used.

to_frame() Return Value

The to_frame() method returns a new DataFrame containing the data from the original Series.


Example 1: Convert Series to a DataFrame

import pandas as pd

# create a Series 
series = pd.Series(['apple', 'banana', 'cherry', 'date'])

# convert the Series to a DataFrame df = series.to_frame()
print("DataFrame:") print(df) # check the type of df using type() print("dtype of df:", type(df))

Output

DataFrame:

0   apple
1  banana
2  cherry
3    date
dtype of df: <class 'pandas.core.frame.DataFrame'>

In the above example, we have created the Series named fruits with string values representing different fruit names.

We used the to_frame() method to convert the fruits Series into a DataFrame. The type() function checks and returns the dtype attribute of the converted dataframe.


Example 2: Convert Series to a DataFrame with a Custom Column Name

import pandas as pd

# create a pandas Series with a name
series = pd.Series([1, 2, 3, 4, 5])

# convert the Series to a DataFrame with a custom column name df = series.to_frame(name='numbers')
print(df)

Output

numbers
0              1
1              2
2              3
3              4
4              5

Here, we converted the Series to a DataFrame using the to_frame() method and specified a custom column name numbers using the name attribute.

The resulting DataFrame df contains a single column named numbers with values from the original Series.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges