Skip to content

BUG: df.explode mulitcol with Nan+emptylist #49680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,7 @@ Reshaping
- Bug in :func:`join` when ``left_on`` or ``right_on`` is or includes a :class:`CategoricalIndex` incorrectly raising ``AttributeError`` (:issue:`48464`)
- Bug in :meth:`DataFrame.pivot_table` raising ``ValueError`` with parameter ``margins=True`` when result is an empty :class:`DataFrame` (:issue:`49240`)
- Clarified error message in :func:`merge` when passing invalid ``validate`` option (:issue:`49417`)
- Bug in :meth:`DataFrame.explode` raising ``ValueError`` on multiple columns with ``NaN`` values or empty lists (:issue:`46084`)

Sparse
^^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -8848,7 +8848,7 @@ def explode(
if len(columns) == 1:
result = df[columns[0]].explode()
else:
mylen = lambda x: len(x) if is_list_like(x) else -1
mylen = lambda x: len(x) if (is_list_like(x) and len(x) > 0) else 1
counts0 = self[columns[0]].apply(mylen)
for c in columns[1:]:
if not all(counts0 == self[c].apply(mylen)):
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/frame/methods/test_explode.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,24 @@ def test_multi_columns(input_subset, expected_dict, expected_index):
result = df.explode(input_subset)
expected = pd.DataFrame(expected_dict, expected_index)
tm.assert_frame_equal(result, expected)


def test_multi_columns_nan_empty():
# GH 46084
df = pd.DataFrame(
{
"A": [[0, 1], [5], [], [2, 3]],
"B": [9, 8, 7, 6],
"C": [[1, 2], np.nan, [], [3, 4]],
}
)
result = df.explode(["A", "C"])
expected = pd.DataFrame(
{
"A": np.array([0, 1, 5, np.nan, 2, 3], dtype=object),
"B": [9, 9, 8, 7, 6, 6],
"C": np.array([1, 2, np.nan, np.nan, 3, 4], dtype=object),
},
index=[0, 0, 1, 2, 3, 3],
)
tm.assert_frame_equal(result, expected)