Skip to content

ENH: Get rid of float cast in masked reduction ops #50833

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 1 commit into from
Jan 19, 2023
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
7 changes: 1 addition & 6 deletions pandas/core/arrays/masked.py
Original file line number Diff line number Diff line change
Expand Up @@ -1081,12 +1081,7 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs):
data = self._data
mask = self._mask

# coerce to a nan-aware float if needed
# (we explicitly use NaN within reductions)
if self._hasna:
data = self.to_numpy("float64", na_value=np.nan)

# median, skew, kurt, idxmin, idxmax
# median, skew, kurt, sem
op = getattr(nanops, f"nan{name}")
result = op(data, axis=0, skipna=skipna, mask=mask, **kwargs)

Expand Down
15 changes: 11 additions & 4 deletions pandas/core/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,15 +758,15 @@ def get_median(x):
res = np.nanmedian(x[mask])
return res

values, mask, dtype, _, _ = _get_values(values, skipna, mask=mask)
values, mask, dtype, _, _ = _get_values(values, skipna, mask=mask, fill_value=0)
if not is_float_dtype(values.dtype):
try:
values = values.astype("f8")
except ValueError as err:
# e.g. "could not convert string to float: 'a'"
raise TypeError(str(err)) from err
if mask is not None:
values[mask] = np.nan
if mask is not None:
values[mask] = np.nan

notempty = values.size

Expand Down Expand Up @@ -1040,8 +1040,11 @@ def nansem(
if not is_float_dtype(values.dtype):
values = values.astype("f8")

if not skipna and mask is not None and mask.any():
return np.nan

count, _ = _get_counts_nanvar(values.shape, mask, axis, ddof, values.dtype)
var = nanvar(values, axis=axis, skipna=skipna, ddof=ddof)
var = nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask)

return np.sqrt(var) / np.sqrt(count)

Expand Down Expand Up @@ -1222,6 +1225,8 @@ def nanskew(
if skipna and mask is not None:
values = values.copy()
np.putmask(values, mask, 0)
elif not skipna and mask is not None and mask.any():
return np.nan

mean = values.sum(axis, dtype=np.float64) / count
if axis is not None:
Expand Down Expand Up @@ -1310,6 +1315,8 @@ def nankurt(
if skipna and mask is not None:
values = values.copy()
np.putmask(values, mask, 0)
elif not skipna and mask is not None and mask.any():
return np.nan

mean = values.sum(axis, dtype=np.float64) / count
if axis is not None:
Expand Down