Skip to content

Commit dd6222f

Browse files
authored
FIX: prevent unnecessary type casts in rolling mean (#10341)
* FIX: use dtype from intermediate sum for casting of count instead of current "int" when calculating mean in rolling operations to prevent unnecessary casting to/from int * Add code comment and whats-new.rst entry
1 parent 7551a7a commit dd6222f

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

doc/whats-new.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ Bug fixes
4545

4646
- Allow accessing arbitrary attributes on Pandas ExtensionArrays.
4747
By `Deepak Cherian <https://github.com/dcherian>`_.
48+
- Use dtype from intermediate sum instead of source dtype or "int" for casting of count when calculating mean in rolling for correct operations (preserve float dtypes, correct mean of bool arrays) (:issue:`10340`, :pull:`10341`).
4849

4950

5051
Documentation

xarray/computation/rolling.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -195,14 +195,15 @@ def method(self, keep_attrs=None, **kwargs):
195195
return method
196196

197197
def _mean(self, keep_attrs, **kwargs):
198-
result = self.sum(keep_attrs=False, **kwargs) / duck_array_ops.astype(
199-
self.count(keep_attrs=False), dtype=int, copy=False
198+
result = self.sum(keep_attrs=False, **kwargs)
199+
# use dtype of result for casting of count
200+
# this allows for GH #7062 and GH #8864, fixes GH #10340
201+
result /= duck_array_ops.astype(
202+
self.count(keep_attrs=False), dtype=result.dtype, copy=False
200203
)
201204
if keep_attrs:
202205
result.attrs = self.obj.attrs
203206

204-
if self.obj.dtype.kind not in "bi":
205-
result = result.astype(self.obj.dtype, copy=False)
206207
return result
207208

208209
_mean.__doc__ = _ROLLING_REDUCE_DOCSTRING_TEMPLATE.format(name="mean")

0 commit comments

Comments
 (0)