set_index(..., append=True) act as with append=False with 'Dimensions without coordinates'
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 4.2k
- Forks
- 1.4k
- Avg merge
- 2d 15h
- Merged PRs (30d)
- 14
Description
What happened:
I get into this strange behaviour when trying to recreate a stacked (MultiIndex) coordinate using set_index(...,append=True).
Since it is not possible to save Dataset to netCDF or Zarr containing stacked / MultiIndex coordinates, before writing to disk I used reset_index(<stacked_coordinate>). When reading such data, I need to use set_index(.., append=True) to recreate such stacked coordinate.
What you expected to happen:
I would expect that set_index(..., append=True) would recreate the MultiIndex stacked coordinate. However, this does not occur if the dimension coordinate specified within set_index() is a 'dimension without coordinate'.
In such situation, set_index(..., append=True) behaves as set_index(, append=False).
Minimal Complete Verifiable Example:
import xarray as xr
import numpy as np
### Create Datasets
arr1 = np.random.rand(4, 5).reshape(4,5)
arr2 = np.random.rand(4, 5).reshape(4,5)
da1 = xr.DataArray(arr1,
dims=['nodes','time'],
coords={"time": [1,2,3,4,5],
"nodes": [1,2,3,4]},
name='var1')
da2 = xr.DataArray(arr2,
dims=['nodes','time'],
coords={"time": [1,2,3,4,5],
"nodes": [1,2,3,4]},
name='var2')
ds_unstacked = xr.Dataset({'var1':da1,'var2':da2})
print(ds_unstacked)
# - Stack variables across a new dimension
da_stacked = ds_unstacked.to_stacked_array(new_dim="variables", variable_dim='variable',
sample_dims=['nodes','time'], name="Stacked_Variables")
ds_stacked = da_stacked.to_dataset()
# - Look at the stacked MultiIndex coordinate 'variables'
print(ds_stacked)
print(da_stacked.variables.indexes)
### Remove MultiIndex (to save Dataset to netCDF/Zarr, ...)
ds_stacked_disk = ds_stacked.reset_index('variables')
print(ds_stacked_disk)
### Try to recreate MultiIndex
print(ds_stacked_disk.set_index(variables=['variable'], append=False)) # GOOD ! Replace 'variable' coordinate with 'variables'
print(ds_stacked_disk.set_index(variables=['variable'], append=True)) # BUG ! Do not create the expected MultiIndex !
### Current workaround to obtain a MultiIndex stacked coordinate
tmp_ds = ds_stacked_disk.assign_coords(variables=(np.arange(0,2)))
ds_stacked1 = tmp_ds.set_index(variables=['variable'], append=True)
print(ds_stacked1) # But with level 0 - 'variables_level_0'
### Unstack back
# - If the BUG is solved, no need to specify the level argument
ds_stacked1['Stacked_Variables'].to_unstacked_dataset(dim='variables', level='variable')
Environment:
Output of xr.show_versions()
INSTALLED VERSIONS
commit: None
python: 3.8.5 | packaged by conda-forge | (default, Sep 24 2020, 16:55:52)
[GCC 7.5.0]
python-bits: 64
OS: Linux
OS-release: 5.4.0-48-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8
libhdf5: 1.10.6
libnetcdf: 4.7.4
xarray: 0.16.1
pandas: 1.1.2
numpy: 1.19.1
scipy: 1.5.2
netCDF4: 1.5.4
pydap: None
h5netcdf: None
h5py: 2.10.0
Nio: None
zarr: 2.5.0
cftime: 1.2.1
nc_time_axis: None
PseudoNetCDF: None
rasterio: None
cfgrib: 0.9.8.4
iris: None
bottleneck: 1.3.2
dask: 2.27.0
distributed: 2.27.0
matplotlib: 3.3.2
cartopy: 0.18.0
seaborn: None
numbagg: None
pint: None
setuptools: 49.6.0.post20200917
pip: 20.2.3
conda: None
pytest: None
IPython: 7.18.1
sphinx: 3.2.1
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the minimal example and inspect Dataset.set_index with append=True after reset_index('variables'). Trace the set_index path for a dimension without a coordinate. Done means append=True recreates the expected MultiIndex, so the stacked data can be unstacked without the temporary coordinate workaround.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- numpy, pandas, python
- Domain
- data
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100