Skip to content

Bug fix - groupby sum removed columns #46342

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
Closed
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
8 changes: 8 additions & 0 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2179,6 +2179,14 @@ def sum(
npfunc=np.sum,
)

if isinstance(result, DataFrame):
Copy link
Contributor

Choose a reason for hiding this comment

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

umm why would this be fix?

try:
dtypes = self.dtypes
for column in result.columns:
result[column] = result[column].astype(dtypes[column].dtype)
except Exception:
pass

return self._reindex_output(result, fill_value=0)

@final
Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
Timestamp,
date_range,
to_datetime,
util,
)
import pandas._testing as tm
from pandas.core.arrays import BooleanArray
Expand Down Expand Up @@ -2654,3 +2655,24 @@ def test_pad_backfill_deprecation():
s.groupby(level=0).backfill()
with tm.assert_produces_warning(FutureWarning, match="pad"):
s.groupby(level=0).pad()


def test_groupby_agg_general_dtypes():
# GH 44132
df = util.testing.makeMixedDataFrame()
df = df.to_numpy()
df = DataFrame(df)
df.columns = ["A", "B", "C", "D"]
df = df.set_index("B")

df1, df2 = df.iloc[:2], df.iloc[2:]

groupby1 = df1.groupby("B").sum()
groupby2 = df2.groupby("B").sum()

df_conc = pd.concat([groupby1, groupby2], axis=0)

result = df_conc.groupby(level=0).sum()
expected = df.groupby(level=0).sum()

tm.assert_frame_equal(result, expected)