pydata / pydata/xarray

unstack is slow for regular data

Open
#11,455 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-performance
Dominant language
Python
Stars
4.2k
Forks
1.4k
Avg merge
2d 15h
Merged PRs (30d)
14

Description

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

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by comparing the unstack entry point with Dataset._unstack_full_reindex(), Variable.unstack(), and the _unstack_once fast path described in the issue. Reproduce the supplied MVCE, then verify that regular MultiIndex unstacking preserves results while approaching the faster full-reindex and reshape timings without regressing missing-value handling.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, pandas, python
Domain
performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.