How do I add another coordinate label in Xarray?

Viewed 83

I have an Xarray, say

da = xr.DataArray([[1,2],[1,2]],coords={'x':['param1','param2'],'y':['idx','idx2']})

This is a 2D data array. As I build out my code, I would like to add another "column" or coordinate label to this 2D dataset. Similar to how in Pandas I can just do

da['param3'] = [1,2]

To add that other column. Is there an equivalent method in Xarray?

1 Answers

I would first create a second dataArray with the new data:

da2 = xr.DataArray([[1,2]],coords={'x':['param3'],'y':['idx','idx2']})

then combine them

da3 = xr.combine_by_coords([da, da2])

You get

<xarray.DataArray (x: 3, y: 2)>
array([[1, 2],
       [1, 2],
       [1, 2]])
Coordinates:
  * x        (x) <U6 'param1' 'param2' 'param3'
  * y        (y) <U4 'idx' 'idx2'
Related