Convert pandas DataFrame to Series in Python (Example)

 

This tutorial demonstrates how to create a pandas Series from a DataFrame in the Python programming language.

The article is structured as follows:

With that, let’s jump right to the example!

 

Example Data & Add-On Libraries

We first have to load the pandas library, in order to use the functions that are contained in the library:

import pandas as pd                   # Load pandas library

As a next step, we’ll also have to create some example pandas DataFrame:

data = pd.DataFrame({'x1':[10],       # Create pandas DataFrame
                     'x2':[20],
                     'x3':[30],
                     'x4':[40],
                     'x5':[50]})
print(data)                           # Print pandas DataFrame

 

table 1 DataFrame convert pandas dataframe series python

 

Have a look at the previous table. It shows that our example data is constituted of one row and five columns.

 

Example: Create pandas Series from DataFrame Using squeeze() Function

The following Python code explains how to convert a pandas DataFrame with one row to a pandas Series in the Python programming language.

For this task, we can use the squeeze function as shown in the following Python code. Within the squeeze function, we have to set the axis argument to be equal to 0:

my_series = data.squeeze(axis = 0)    # Apply squeeze
print(my_series)                      # Print pandas Series
# x1    10
# x2    20
# x3    30
# x4    40
# x5    50
# Name: 0, dtype: int64

Have a look at the previous console output: We have created a pandas Series containing the values from our input data set.

 

Video, Further Resources & Summary

In case you need more explanations on the topics of this tutorial, I recommend watching the following video on my YouTube channel. In the video, I illustrate the examples of this page in Python:

 

 

Furthermore, you could have a look at some of the related Python posts on my website:

 

In this tutorial, I have demonstrated how to transform a pandas DataFrame to a Series in Python programming. In case you have further questions, let me know in the comments.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top