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
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:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you could have a look at some of the related Python posts on my website:
- Handling DataFrames Using the pandas Library in Python
- Convert Series to pandas DataFrame in Python
- Convert pandas DataFrame to List in Python
- Convert Index to Column of pandas DataFrame in Python
- Convert pandas DataFrame Index to List & NumPy Array in Python
- Convert pandas DataFrame to NumPy Array in Python
- Convert pandas DataFrame Column to datetime in Python
- Python Programming Examples
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.