Convert Series of lists to one Series in Pandas

Convert Series of lists to one Series in Pandas

To convert a Pandas Series containing lists into a single Series with each element of the lists, you can use the explode() method. This method transforms each element of a list-like to a row, replicating the index values.

Here's a step-by-step guide on how to do this:

Step 1: Create a Pandas Series of Lists

First, create a Pandas Series where each element is a list. If you already have this Series, you can skip this step.

import pandas as pd data = [[1, 2, 3], [4, 5], [6], [7, 8]] series_of_lists = pd.Series(data) 

Step 2: Explode the Series

Use the explode() method to convert the Series of lists into a single Series.

exploded_series = series_of_lists.explode() 

Example

Putting it all together:

import pandas as pd # Sample Series of lists data = [[1, 2, 3], [4, 5], [6], [7, 8]] series_of_lists = pd.Series(data) # Convert to a single Series exploded_series = series_of_lists.explode() print(exploded_series) 

Output

The output will be a single Series with each element of the lists:

0 1 0 2 0 3 1 4 1 5 2 6 3 7 3 8 dtype: object 

Notes

  • The explode() method is available in Pandas version 0.25.0 and later. Ensure you have an appropriate version of Pandas if you want to use this method.
  • The index of the new Series corresponds to the index of the original list elements in the Series. If you need a reset index, you can use exploded_series.reset_index(drop=True).
  • This method is particularly useful when dealing with data that's been grouped into lists but needs to be analyzed or processed individually.

More Tags

chai video-player tooltip sitecore search rabbitmqctl to-char jsonparser scrollbar primeng-datatable

More Programming Guides

Other Guides

More Programming Examples