-
-
Notifications
You must be signed in to change notification settings - Fork 18.9k
[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
base: 2.3.x
Are you sure you want to change the base?
Conversation
…or string dtype (empty string instead of 0) (pandas-dev#61909)
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 |
There was a problem hiding this comment.
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?)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yea - I don't see any nice solution here, I'm good with the above. Just have the CI failing.
Backport of #61909