Skip to content

DataSetRolling and DatasetGroupBy silently accept keepdims, which modifes shape of the GroupBy output #11518

Description

@charles-turner-1

What happened?

Note

I've edited this a bit since I've opened it since I've discovered a bit of a can of worms. I'm trying to figure out if this is a duplicate of other issues now - it wasn't when I started.

tldr; ds.rolling({'time' : 12}).mean(keepdims=False|True) makes no difference and doesn't raise or even warn - plus some other related oddities.

To my mind, it should probably at least warn?

Bit of a corner case, found it whilst working on expression rewriting

What did you expect to happen?

At a minimum, probably raise for keepdims=False and warn for keepdims=True, or in an ideal world raise for both with a TypeError?

Minimal Complete Verifiable Example

# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "xarray[complete]@git+https://github.com/pydata/xarray.git@main",
# ]
# ///
#
# This script automatically imports the development branch of xarray to check for issues.
# Please delete this header if you have _not_ tested this script with `uv run`!

import numpy as np
import pandas as pd
import xarray as xr
from xarray.testing import assert_equal

xr.show_versions()

# Create a toy dataset over time

time_range = pd.date_range("2000-01-01", "2019-12-31", freq="MS")

tas = np.random.rand(
    len(time_range),
)

# Create an xarray Dataset
ds = xr.Dataset(
    {
        "tas": (
            ["time",],
            tas,
        ),
    },
    coords={
        "time": time_range,
    },
)

print("This pops out a warning noting that dim kwarg has no effect")
ds.rolling({"time": 12}).mean(dim="time")

print("This doesn't pop out any warning, just silently ignoring it")
_keepdims = ds.rolling({"time": 12}).mean(keepdims=False)
_no_keepdims = ds.rolling({"time": 12}).mean(keepdims=True)


print("Using `xr.testing.assert_equal` to check that the two results are equal")
assert_equal(_keepdims, _no_keepdims)
print("----------")
print(_keepdims)

outputs

This pops out a warning noting that dim kwarg has no effect
/Users/u1166368/.cache/uv/environments-v2/uv-repro-cae15bde6b41ecb3/lib/python3.12/site-packages/xarray/computation/rolling.py:919: FutureWarning: Reductions are applied along the rolling dimension(s) '['time']'. Passing the 'dim' kwarg to reduction operations has no effect.
  return self._dataset_implementation(
This doesn't pop out any warning, jut silently ignoring it
Using `xr.testing.assert_equal` to check that the two results are equal
----------
<xarray.Dataset> Size: 4kB
Dimensions:  (time: 240)
Coordinates:
  * time     (time) datetime64[us] 2kB 2000-01-01 2000-02-01 ... 2019-12-01
Data variables:
    tas      (time) float64 2kB nan nan nan nan ... 0.4684 0.4808 0.4134 0.4793

Steps to reproduce

Run the script above

MVCE confirmation

  • Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
  • Complete example — the example is self-contained, including all data and the text of any traceback.
  • Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
  • New issue — a search of GitHub Issues suggests this is not a duplicate.
  • Recent environment — the issue occurs with the latest version of xarray and its dependencies.

Relevant log output

Anything else we need to know?

I think this this is related to #6772.

I'll take a crack at solving this when I get some time

Environment

Details

INSTALLED VERSIONS

commit: None
python: 3.14.6 | packaged by conda-forge | (main, Aug 11 2026, 10:24:52) [Clang 20.1.8 ]
python-bits: 64
OS: Darwin
OS-release: 24.5.0
machine: arm64
processor: arm
byteorder: little
LC_ALL: None
LANG: en_AU.UTF-8
LOCALE: ('en_AU', 'UTF-8')
libhdf5: None
libnetcdf: None

xarray: 2026.7.0
pandas: 3.0.5
numpy: 2.5.2
scipy: None
netCDF4: None
pydap: None
h5netcdf: None
h5py: None
zarr: None
cftime: None
nc_time_axis: None
iris: None
bottleneck: None
dask: None
distributed: None
matplotlib: 3.11.1
cartopy: None
seaborn: None
numbagg: None
fsspec: None
cupy: None
pint: None
sparse: None
flox: None
numpy_groupies: None
setuptools: None
pip: None
conda: None
pytest: None
mypy: None
IPython: None
sphinx: None


Where this gets a bit weirder

(This is the stuff that grew out of #11519, which I thought was originally a docs mismatch and now looks more like a related family of bugs - works on all reductions on groupbys)

For brevity, I'm going to keep the code snippets shorter - but all of these are in that same environment as above. We'll use a slightly more realistic dataset:

>>> time_range = pd.date_range("2000-01-01","2019-12-31", freq="MS")
>>> lat = np.linspace(-90, 90, 10)
>>> lon = np.linspace(-180, 180, 10)

>>> tas = np.random.rand(len(time_range), len(lat), len(lon))
>>> ds = xr.Dataset(
    {
        "tas": ([
            "time",
            "lat",
            "lon",
           ], tas),
    },
    coords={
        "time": time_range,
        "lat": lat,
        "lon": lon,
    },
)
>>> print(ds)
<xarray.Dataset> Size: 194kB
Dimensions:  (time: 240, lat: 10, lon: 10)
Coordinates:
  * time     (time) datetime64[us] 2kB 2000-01-01 2000-02-01 ... 2019-12-01
  * lat      (lat) float64 80B -90.0 -70.0 -50.0 -30.0 ... 30.0 50.0 70.0 90.0
  * lon      (lon) float64 80B -180.0 -140.0 -100.0 -60.0 ... 100.0 140.0 180.0
Data variables:
    tas      (time, lat, lon) float64 192kB 0.8188 0.1303 ... 0.3642 0.2258

To be concrete, the following are on type(ds.groupby("time.month")) == <class 'xarray.core.groupby.DatasetGroupBy'>
Firstly, as expected:

>>> ds.groupby("time.month").mean()
<xarray.Dataset> Size: 10kB
Dimensions:  (month: 12, lat: 10, lon: 10)
Coordinates:
  * month    (month) int64 96B 1 2 3 4 5 6 7 8 9 10 11 12
  * lat      (lat) float64 80B -90.0 -70.0 -50.0 -30.0 ... 30.0 50.0 70.0 90.0
  * lon      (lon) float64 80B -180.0 -140.0 -100.0 -60.0 ... 100.0 140.0 180.0
Data variables:
    tas      (month, lat, lon) float64 10kB 0.5994 0.4576 ... 0.5112 0.4504

Now if we specify keepdims=True:

>>> ds.groupby("time.month").mean(keepdims=True)
<xarray.Dataset> Size: 10kB
Dimensions:  (time: 12, lat: 10, lon: 10)
Coordinates:
  * lat      (lat) float64 80B -90.0 -70.0 -50.0 -30.0 ... 30.0 50.0 70.0 90.0
  * lon      (lon) float64 80B -180.0 -140.0 -100.0 -60.0 ... 100.0 140.0 180.0
Dimensions without coordinates: time
Data variables:
    tas      (time, lat, lon) float64 10kB 0.5994 0.4576 ... 0.5112 0.4504

So in this instance, keepdims=True has:

  • Stopped the 'renaming' (term used loosely) of time => month
  • Stopped the creation of the month coordinate
  • Stopped the creation of any coordinates over the remaining time dimension

This also works without the kind of mapping approach (I know this is dumb and unlikely but just for completeness):

print(ds.groupby("time").mean(keepdims=True))
<xarray.Dataset> Size: 192kB
Dimensions:  (time: 240, lat: 10, lon: 10)
Coordinates:
  * lat      (lat) float64 80B -90.0 -70.0 -50.0 -30.0 ... 30.0 50.0 70.0 90.0
  * lon      (lon) float64 80B -180.0 -140.0 -100.0 -60.0 ... 100.0 140.0 180.0
Dimensions without coordinates: time
Data variables:
    tas      (time, lat, lon) float64 192kB 0.8188 0.1303 ... 0.3642 0.2258

This seems at odds with what happens with DatasetRolling.mean() ignoring the keepdims Flag (which feels like a very benign bug to me - it's kinda meaningless to set keepdims to False with it), but I think it's also meaningfully an actual bug? Definitely a bit of an edge case - but the results don't really make sense as they stand. I think fix for this second issue with DatasetGroupBy would be to either:

  • Explictly disallow keepdims on groupby()...
  • Put the coordinate back in?

I can see cases for either - both make sense to me. For consistency with the rolling version, I think explicitly disallowing it for both would be the way to go? It doesn't make a great deal of sense for either & does weird things.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugneeds triageIssue that has not been reviewed by xarray team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions