jammertheprogrammer
jammertheprogrammer

Reputation: 397

How can I relabel an xarry DataArray?

I have a DataArray that looks like this:

<xarray.DataArray (rows: 3, cols: 3)>
array([[11, 12, 13],
       [21, 22, 23],
       [31, 32, 33]])
Coordinates:
  * rows     (rows) <U5 'row1' 'row2' 'row3'
  * cols     (cols) <U4 'col1' 'col2' 'col3'

How can I change the labels to get:

<xarray.DataArray (rows: 3, cols: 3)>
array([[11, 12, 13],
       [21, 22, 23],
       [31, 32, 33]])
Coordinates:
  * rows     (rows) <U5 'rowA' 'rowB' 'rowC'
  * cols     (cols) <U4 'col1' 'col2' 'col3'

I try to use test.rename({"row1":"rowA", "row2":"rowB", "row3":"rowC"}) but it gives me a ValueError:

ValueError: cannot rename 'row1' because it is not a variable or dimension in this dataset

I take it that rename is just simply meant for dimension names, but if that is the case then the documentation does not make that clear at all.

Upvotes: 0

Views: 163

Answers (1)

Maximilian
Maximilian

Reputation: 8530

This is probably the easiest approach currently. It's not as nice as pandas' options for this at the moment, and we'd be interested in making it easier. In particular, we'd be very open to a PR making the documentation clearer per your feedback.

In [8]: da = xr.DataArray([1,2,3], coords=dict(a=list('xyz')), dims=['a'])
    
In [10]: da
Out[10]:
<xarray.DataArray (a: 3)>
array([1, 2, 3])
Coordinates:
  * a        (a) <U1 'x' 'y' 'z'

In [9]: da.to_dataset('a').rename(x='x2').to_array('a')
Out[9]:
<xarray.DataArray (a: 3)>
array([1, 2, 3])
Coordinates:
  * a        (a) <U2 'x2' 'y' 'z'

Upvotes: 1

Related Questions