Is it possible to assign a list of tuples as a coordinate?

716 views
Skip to first unread message

Ian Liu Rodrigues

unread,
Feb 8, 2022, 2:27:47 PM2/8/22
to xarray
I would like to model a matrix in which one of its dimensions is indexed by a tuple, for instance:

tiles = [(1, 10), (2, 5)]
xarray.DataArray(
    numpy.zeros((len(tiles), 3, 2), dtype=int),
    dims=("tile", "y", "x"),
    coords={
        "tile": tiles,
        "y": [0, 1, 2],
        "x": [0, 1],
    })


but this fails with:

MissingDimensionsError: cannot set variable 'tile' with 2-dimensional data without explicit dimension names. Pass a tuple of (dims, data) instead.

Is it possible to index with tuples?

Thanks,
Ian L.

Justus Magin

unread,
Feb 8, 2022, 2:37:56 PM2/8/22
to xar...@googlegroups.com
Hi Ian,

It is possible, we just have to make sure it fits into a `numpy` array:

```python
In [10]: tiles = np.empty(shape=(2,), dtype=object)
...: tiles[:] = [(1, 10), (2, 5)]
...:
...: xr.DataArray(
...: np.zeros((len(tiles), 3, 2), dtype=int),
...: dims=("tile", "y", "x"),
...: coords={
...: "tile": tiles,
...: "y": [0, 1, 2],
...: "x": [0, 1],
...: },
...: )
Out[10]:
<xarray.DataArray (tile: 2, y: 3, x: 2)>
array([[[0, 0],
[0, 0],
[0, 0]],

[[0, 0],
[0, 0],
[0, 0]]])
Coordinates:
* tile (tile) object (1, 10) (2, 5)
* y (y) int64 0 1 2
* x (x) int64 0 1
```

Not sure if there is a way to construct `tiles` directly, though.

Cheers,
Justus

Ian Liu Rodrigues

unread,
Feb 9, 2022, 6:37:27 AM2/9/22
to xar...@googlegroups.com
Em ter., 8 de fev. de 2022 às 16:37, Justus Magin <kee...@posteo.de> escreveu:
> Hi Ian,
> It is possible, we just have to make sure it fits into a `numpy` array:

Thanks! I've managed to achieve the same with

coords = { "tile": numpy.array(tiles, dtype="i,i"), ...}

Ian Liu Rodrigues
PGP 0xf1e1f46d8315b893
Reply all
Reply to author
Forward
0 new messages