Overview
- The explode() method of pandas Series class makes a row out of each element present in the Series and returns the new series.
- If the Series object has any sequences contained inside, each element present inside them (like a tuple, list, pandas Series and ndarray) are made as a separate row with the index of the sequence as the index of the new element.
Example
import pandas as pds
# A heterogeneous list
hetero = ["a", 1, 3.14, (2, 3, 5, 7), ["x", "y", "z"]];
# Create a pandas series from the list
series = pds.Series(hetero);
# Make the series flat
newSeries = series.explode();
print("Original Series:");
print(series);
print("Types of elements present in the pandas series:");
for element in hetero:
print(type(element));
print("New Series:");
print(newSeries);
print("Types of elements present in the new series returned by calling explode():");
for element in newSeries:
print(type(element));Output
Original Series:
0 a
1 1
2 3.14
3 (2, 3, 5, 7)
4 [x, y, z]
dtype: object
Types of elements present in the pandas series:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'tuple'>
<class 'list'>
New Series:
0 a
1 1
2 3.14
3 2
3 3
3 5
3 7
4 x
4 y
4 z
dtype: object
Types of elements present in the new series returned by calling explode():
<class 'str'>
<class 'int'>
<class 'float'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'str'>
<class 'str'>
<class 'str'>