Skip to content

[backport 2.3.x] BUG: fix fill value for gouped sum in case of unobserved categories for string dtype (empty string instead of 0) (#61909) #61963

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

Open
wants to merge 3 commits into
base: 2.3.x
Choose a base branch
from

Conversation

jorisvandenbossche
Copy link
Member

Backport of #61909

Comment on lines +5639 to +5656
if using_string_dtype() and method == "sum":
if isinstance(output, Series) and isinstance(output.dtype, StringDtype):
d["fill_value"] = ""
return output.reindex(**d) # type: ignore[arg-type]
elif isinstance(output, DataFrame) and any(
isinstance(dtype, StringDtype) for dtype in output.dtypes
):
orig_dtypes = output.dtypes
indices = np.nonzero(output.dtypes == "string")[0]
for idx in indices:
output.isetitem(idx, output.iloc[:, idx].astype(object))
output = output.reindex(**d)
for idx in indices:
col = output.iloc[:, idx]
output.isetitem(
idx, col.mask(col == 0, "").astype(orig_dtypes.iloc[idx])
)
return output
Copy link
Member Author

@jorisvandenbossche jorisvandenbossche Aug 20, 2025

Choose a reason for hiding this comment

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

The original fix from the PR does not actually work for the 2.3.x branch, because here we still have the _reindex_output helper method to deal with the observed=False case.

And then we have the problem that output.reindex(..) doesn't work if you want to fill with multiple fill values (0 for numerical columns, "" for string columns). The above is a bit an ugly solution, but I also don't directly know a cleaner way how to do this with the current pandas APIs .. (and given this is only for 2.3.x and not to keep forever, and only behind the option flag, it's maybe OK?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants