Skip to content

Change mylen function to account for NaN empty lists when exploding on multiple columns #46791

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

Closed
wants to merge 11 commits into from
Closed
2 changes: 1 addition & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -9012,7 +9012,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
48 changes: 37 additions & 11 deletions pandas/tests/frame/methods/test_explode.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,9 +223,15 @@ def test_explode_sets():


@pytest.mark.parametrize(
"input_subset, expected_dict, expected_index",
"input_dict, input_index, input_subset, expected_dict, expected_index",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you make new tests? This is really hard to review

[
(
{
"A": [[0, 1, 2], np.nan, [], (3, 4), np.nan],
"B": 1,
"C": [["a", "b", "c"], "foo", [], ["d", "e"], np.nan],
},
list("abcde"),
list("AC"),
{
"A": pd.Series(
Expand All @@ -239,6 +245,12 @@ def test_explode_sets():
list("aaabcdde"),
),
(
{
"A": [[0, 1, 2], np.nan, [], (3, 4), np.nan],
"B": 1,
"C": [["a", "b", "c"], "foo", [], ["d", "e"], np.nan],
},
list("abcde"),
list("A"),
{
"A": pd.Series(
Expand All @@ -260,18 +272,32 @@ def test_explode_sets():
},
list("aaabcdde"),
),
(
{
"A": [[0, 1, 2], [], np.nan, [], (3, 4), np.nan, []],
"B": 1,
"C": [["a", "b", "c"], 2, "foo", [], ["d", "e"], np.nan, np.nan],
},
list("abcdefg"),
list("AC"),
{
"A": pd.Series(
[0, 1, 2, np.nan, np.nan, np.nan, 3, 4, np.nan, np.nan],
index=list("aaabcdeefg"),
dtype=object,
),
"B": 1,
"C": ["a", "b", "c", 2, "foo", np.nan, "d", "e", np.nan, np.nan],
},
list("aaabcdeefg"),
),
],
)
def test_multi_columns(input_subset, expected_dict, expected_index):
# GH 39240
df = pd.DataFrame(
{
"A": [[0, 1, 2], np.nan, [], (3, 4), np.nan],
"B": 1,
"C": [["a", "b", "c"], "foo", [], ["d", "e"], np.nan],
},
index=list("abcde"),
)
def test_multi_columns(
input_dict, input_index, input_subset, expected_dict, expected_index
):
# GH 39240, 46084
df = pd.DataFrame(input_dict, input_index)
result = df.explode(input_subset)
expected = pd.DataFrame(expected_dict, expected_index)
tm.assert_frame_equal(result, expected)