- API reference
- DataFrame
- pandas.DataF...
pandas.DataFrame.explode#
- DataFrame.explode(column,ignore_index=False)[source]#
Transform each element of a list-like to a row, replicating index values.
- Parameters:
- columnIndexLabel
Column(s) to explode.For multiple columns, specify a non-empty list with each elementbe str or tuple, and all specified columns their list-like dataon same row of the frame must have matching length.
Added in version 1.3.0:Multi-column explode
- ignore_indexbool, default False
If True, the resulting index will be labeled 0, 1, …, n - 1.
- Returns:
- DataFrame
Exploded lists to rows of the subset columns;index will be duplicated for these rows.
- Raises:
- ValueError
If columns of the frame are not unique.
If specified columns to explode is empty list.
If specified columns to explode have not matching count ofelements rowwise in the frame.
See also
DataFrame.unstack
Pivot a level of the (necessarily hierarchical) index labels.
DataFrame.melt
Unpivot a DataFrame from wide format to long format.
Series.explode
Explode a DataFrame from list-like columns to long format.
Notes
This routine will explode list-likes including lists, tuples, sets,Series, and np.ndarray. The result dtype of the subset rows willbe object. Scalars will be returned unchanged, and empty list-likes willresult in a np.nan for that row. In addition, the ordering of rows in theoutput will be non-deterministic when exploding sets.
Referencethe user guide for more examples.
Examples
>>>df=pd.DataFrame({'A':[[0,1,2],'foo',[],[3,4]],...'B':1,...'C':[['a','b','c'],np.nan,[],['d','e']]})>>>df A B C0 [0, 1, 2] 1 [a, b, c]1 foo 1 NaN2 [] 1 []3 [3, 4] 1 [d, e]
Single-column explode.
>>>df.explode('A') A B C0 0 1 [a, b, c]0 1 1 [a, b, c]0 2 1 [a, b, c]1 foo 1 NaN2 NaN 1 []3 3 1 [d, e]3 4 1 [d, e]
Multi-column explode.
>>>df.explode(list('AC')) A B C0 0 1 a0 1 1 b0 2 1 c1 foo 1 NaN2 NaN 1 NaN3 3 1 d3 4 1 e