Convert Series of lists to one Series in Pandas

Given a series of lists, we have to convert it into one series in Python pandas.
Submitted by Pranit Sharma, on October 21, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

We are given a DataFrame, this dataframe contains a column that only has values in the form of a list. This single column will act as a series and hence this series is a series of the list, now the list varies by length as each list has a different number of elements. We need to collapse all these elements into one series.

Converting Series of lists to one Series

For this purpose, we will first create a DataFrame, then we will convert this column into a series, and then finally will apply the stack() method on this series and reset the indices.

Let us understand with the help of an example,

Python program to convert series of lists to one series

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating a dictionary
d = {'col':[[1,2,3],[1,2,3,4],[1,2]]}

# Creating DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original Dataframe :\n",df,"\n")

# Creating a series
s = pd.Series(df['col'])

# Collapsing the elements if series
res = s.apply(pd.Series).stack().reset_index(drop=True)

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Convert Series of lists to one Series in Pandas

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.