w3resource

Pandas Data Series: Convert Series of lists to one Series

Pandas: Data Series Exercise-10 with Solution

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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/python-pandas-data-series-exercise-10.php