Pandas Data Series: Convert Series of lists to one Series
10. Flatten Series of Lists
Write a Pandas program to convert Series of lists to one Series.
Sample Solution :
Python Code :
import pandas as pd
s = pd.Series([
['Red', 'Green', 'White'],
['Red', 'Black'],
['Yellow']])
print("Original Series of list")
print(s)
s = s.apply(pd.Series).stack().reset_index(drop=True)
print("One Series")
print(s)
Sample Output:
Original Series of list 0 [Red, Green, White] 1 [Red, Black] 2 [Yellow] dtype: object One Series 0 Red 1 Green 2 White 3 Red 4 Black 5 Yellow dtype: object
Explanation:
s = pd.Series([ ['Red', 'Green', 'White'], ['Red', 'Black'], ['Yellow']]) : This line creates a Pandas Series object 's' containing a sequence of three lists of strings.
s = s.apply(pd.Series).stack().reset_index(drop=True)
In the above code:
s.apply(pd.Series): Applies the pd.Series() constructor to each element of the Pandas Series object 's' using the .apply() method. This converts each list element into a separate Pandas Series object with one row per element.
Output: 0 1 2 0 Red Green White 1 Red Black NaN 2 Yellow NaN NaN s.apply(pd.Series).stack(): The .stack() method is then applied to the resulting object. The resulting object will have a hierarchical index with the original index and a secondary index for each element of the original lists. Output: 0 0 Red 1 Green 2 White 1 0 Red 1 Black 2 0 Yellow dtype: object s.apply(pd.Series).stack().reset_index(drop=True): Finally the .reset_index() method with the 'drop' parameter set to True is then applied to reset the index of the Series object 's' and drop the old index. Output: 0 Red 1 Green 2 White 3 Red 4 Black 5 Yellow dtype: object
For more Practice: Solve these Related Problems:
- Write a Pandas program to flatten a Series where each element is a list of numbers and remove duplicates.
- Write a Pandas program to convert a Series of comma-separated strings into a flat Series of trimmed strings.
- Write a Pandas program to flatten a Series containing nested lists and then sort the result.
- Write a Pandas program to flatten a Series of lists and then count the frequency of each unique element.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to convert a given Series to an array.
Next: Write a Pandas program to sort a given Series.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.