Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit fc66d10

Browse files
committedJul 17, 2019
multi-index column support
1 parent d38f7d8 commit fc66d10

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed
 

‎pandas/core/frame.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import itertools
1616
import sys
1717
from textwrap import dedent
18-
from typing import FrozenSet, List, Optional, Set, Type, Union
18+
from typing import FrozenSet, List, Optional, Set, Tuple, Type, Union
1919
import warnings
2020

2121
import numpy as np
@@ -6233,7 +6233,7 @@ def stack(self, level=-1, dropna=True):
62336233
else:
62346234
return stack(self, level, dropna=dropna)
62356235

6236-
def explode(self, column: str) -> "DataFrame":
6236+
def explode(self, column: Union[str, Tuple]) -> "DataFrame":
62376237
"""
62386238
Transform each element of a list-like to a row, replicating the
62396239
index values.
@@ -6242,7 +6242,7 @@ def explode(self, column: str) -> "DataFrame":
62426242
62436243
Parameters
62446244
----------
6245-
column : str
6245+
column : str or tuple
62466246
62476247
Returns
62486248
-------
@@ -6290,7 +6290,7 @@ def explode(self, column: str) -> "DataFrame":
62906290
3 4 1
62916291
"""
62926292

6293-
if not is_scalar(column):
6293+
if not (is_scalar(column) or isinstance(column, tuple)):
62946294
raise ValueError("column must be a scalar")
62956295
if not self.columns.is_unique:
62966296
raise ValueError("columns must be unique")

‎pandas/tests/frame/test_explode.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def test_basic():
3333
tm.assert_frame_equal(result, expected)
3434

3535

36-
def test_multi_index():
36+
def test_multi_index_rows():
3737
df = pd.DataFrame(
3838
{"A": np.array([[0, 1, 2], np.nan, [], (3, 4)], dtype=object), "B": 1},
3939
index=pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), ("b", 2)]),
@@ -63,6 +63,25 @@ def test_multi_index():
6363
tm.assert_frame_equal(result, expected)
6464

6565

66+
def test_multi_index_columns():
67+
df = pd.DataFrame(
68+
{("A", 1): np.array([[0, 1, 2], np.nan, [], (3, 4)], dtype=object), ("A", 2): 1}
69+
)
70+
71+
result = df.explode(("A", 1))
72+
expected = pd.DataFrame(
73+
{
74+
("A", 1): pd.Series(
75+
[0, 1, 2, np.nan, np.nan, 3, 4],
76+
index=pd.Index([0, 0, 0, 1, 2, 3, 3]),
77+
dtype=object,
78+
),
79+
("A", 2): 1,
80+
}
81+
)
82+
tm.assert_frame_equal(result, expected)
83+
84+
6685
def test_usecase():
6786
# explode a single column
6887
# gh-10511

0 commit comments

Comments
 (0)
Please sign in to comment.