Skip to content

BUG: groupby.apply on the NaN group drops values with original axes return #38257

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 4 commits into from
Dec 4, 2020
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/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrame.groupby` dropped ``nan`` groups from result with ``dropna=False`` when grouping over a single column (:issue:`35646`, :issue:`35542`)
- Bug in :meth:`.DataFrameGroupBy.head`, :meth:`.DataFrameGroupBy.tail`, :meth:`SeriesGroupBy.head`, and :meth:`SeriesGroupBy.tail` would raise when used with ``axis=1`` (:issue:`9772`)
- Bug in :meth:`.DataFrameGroupBy.transform` would raise when used with ``axis=1`` and a transformation kernel (e.g. "shift") (:issue:`36308`)
- Bug in :meth:`.DataFrameGroupBy.apply` dropped values on ``nan`` group when returning the same axes with the original frame (:issue:`38227`)
- Bug in :meth:`.DataFrameGroupBy.quantile` couldn't handle with arraylike ``q`` when grouping by columns (:issue:`33795`)
- Bug in :meth:`DataFrameGroupBy.rank` with ``datetime64tz`` or period dtype incorrectly casting results to those dtypes instead of returning ``float64`` dtype (:issue:`38187`)

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1216,7 +1216,7 @@ def reset_identity(values):

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

# this is a very unfortunate situation
# we can't use reindex to restore the original order
Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1087,3 +1087,25 @@ def test_apply_by_cols_equals_apply_by_rows_transposed():

tm.assert_frame_equal(by_cols, by_rows.T)
tm.assert_frame_equal(by_cols, df)


def test_apply_dropna_with_indexed_same():
# GH 38227

df = DataFrame(
{
"col": [1, 2, 3, 4, 5],
"group": ["a", np.nan, np.nan, "b", "b"],
},
index=list("xxyxz"),
)
result = df.groupby("group").apply(lambda x: x)
expected = DataFrame(
{
"col": [1, 4, 5],
"group": ["a", "b", "b"],
},
index=list("xxz"),
)

tm.assert_frame_equal(result, expected)