Skip to content

BUG: groupby.apply incorrectly dropping nan #43236

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 11 commits into from
Sep 6, 2021
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Fixed regressions
- Fixed regression in :class:`DataFrame` constructor failing to broadcast for defined :class:`Index` and len one list of :class:`Timestamp` (:issue:`42810`)
- Performance regression in :meth:`core.window.ewm.ExponentialMovingWindow.mean` (:issue:`42333`)
- Fixed regression in :meth:`.GroupBy.agg` incorrectly raising in some cases (:issue:`42390`)
-
- Fixed regression in :meth:`.GroupBy.apply` where ``nan`` values were dropped even with ``dropna=False`` (:issue:`43205`)

.. ---------------------------------------------------------------------------

Expand Down
6 changes: 5 additions & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1010,7 +1010,11 @@ def reset_identity(values):

if not not_indexed_same:
result = concat(values, axis=self.axis)
ax = self.filter(lambda x: True).axes[self.axis]
ax = (
self.filter(lambda x: True).axes[self.axis]
if self.dropna
else self._selected_obj._get_axis(self.axis)
)

# this is a very unfortunate situation
# we can't use reindex to restore the original order
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1150,3 +1150,17 @@ def test_doctest_example2():
{"B": [1.0, 0.0], "C": [2.0, 0.0]}, index=Index(["a", "b"], name="A")
)
tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize("dropna", [True, False])
def test_apply_dropna_with_indexed_same2(dropna):
Copy link
Member

Choose a reason for hiding this comment

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

This test completely supersedes the other test_apply_dropna_with_indexed test; can you just apply the parametrization and the expected change to that test.

Copy link
Member Author

Choose a reason for hiding this comment

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

Amended.
Let me know how this looks.

# GH#43205
df = DataFrame(
{
"a": [1, 2, 3, 4, 5, 6, 7, 8, 9],
"b": [1, np.nan, 1, np.nan, 2, 1, 2, np.nan, 1],
}
)
result = df.groupby("b", dropna=dropna).apply(lambda x: x)
expected = df.dropna() if dropna else df
tm.assert_frame_equal(result, expected)