Skip to content

unstack is slow for regular data #11455

Description

@takluyver

What happened?

Unstacking an array with a 'regular' MultiIndex, i.e. a cartesian product which doesn't need any missing value handling, is unexpectedly slow.

E.g. unstacking (300_000, 1024) -> (10_000, 30, 1024) takes ~660 ms in my test, whereas reshaping the numpy array is massively quicker.

What did you expect to happen?

Where possible, I'd like unstack to make a view rather than a copy. I know it won't match the performance of reshape because it has to deal with coordinates etc., but it could be a lot closer.

xarray actually already has the code to do what I want, in Dataset._unstack_full_reindex() and Variable.unstack(). If I call ._unstack_full_reindex() by hand, I get a significant speedup. But unstack prefers the "fast path" _unstack_once added in #4746, which is not fast in this scenario:

Image

IIUC, _unstack_once is meant to speed up dealing with missing values, when a new array has to be allocated. But unfortunately it always allocates a new array and copies the data across, even if there are no missing values to handle.

Minimal Complete Verifiable Example

import time
import pandas as pd
import xarray as xr

xr.show_versions()

da = xr.DataArray(data=np.ones((300_000, 1024)), dims=["midx", "other"], coords={
    "midx": pd.MultiIndex.from_product([range(10_000), range(30)])
})

t0 = time.perf_counter()

da.unstack()
t1 = time.perf_counter()

da.values.reshape(10_000, 30, 1024)
t2 = time.perf_counter()

tds = da.to_dataset(name="tmp")
tds._unstack_full_reindex('midx', tds._get_stack_index('midx', multi=True), xr.core.dtypes.NA, False)['tmp']
t3 = time.perf_counter()

print(f"unstack: {t1-t0:.4g} s")
print(f"reshape: {t2-t1:.4g} s")
print(f"_unstack_full_reindex: {t3-t2:.4g} s")

Steps to reproduce

No response

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

unstack: 0.6793 s
reshape: 6.684e-05 s
_unstack_full_reindex: 0.02158 s

Anything else we need to know?

No response

Environment

Details

INSTALLED VERSIONS

commit: None
python: 3.11.13 | packaged by conda-forge | (main, Jun 4 2025, 14:48:23) [GCC 13.3.0]
python-bits: 64
OS: Linux
OS-release: 5.14.0-687.25.1.el9_8.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: ('en_US', 'UTF-8')
libhdf5: 1.14.6
libnetcdf: 4.9.2

xarray: 2025.6.1
pandas: 2.3.0
numpy: 1.26.4
scipy: 1.16.0
netCDF4: 1.7.2
pydap: None
h5netcdf: 1.6.3
h5py: 3.14.0
zarr: 3.0.9
cftime: 1.6.4
nc_time_axis: None
iris: None
bottleneck: 1.5.0
dask: 2025.5.1
distributed: 2025.5.1
matplotlib: 3.8.2
cartopy: None
seaborn: 0.13.2
numbagg: None
fsspec: 2025.5.1
cupy: None
pint: 0.24.4
sparse: None
flox: None
numpy_groupies: None
setuptools: 80.9.0
pip: 26.0.1
conda: None
pytest: 8.4.1
mypy: None
IPython: 8.21.0
sphinx: 7.3.7

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions