Reputation: 4886
Assume the following code, which has an xarray.DataArray
with two dimensions and a coordinate:
import numpy as np
from xarray import DataArray
data = np.random.rand(10, 4)
f_names = ['a', 'b', 'c', 'd']
sample_weights = np.random.rand(10)
rows = list(range(len(data)))
coords={'samples': rows,
'features': f_names,
'sample_weights': ('samples', sample_weights)}
xdata = DataArray(data, coords=coords,
dims=['samples', 'features'])
subset = xdata[::2]
Now I want to add another coordinates, like alternate_sample_weights
to subset
. I try:
subset.assign_coords(alternate_sample_weights=np.zeros(5)
which results in the following error:
ValueError: cannot add coordinates with new dimensions to a DataArray
The API documentation is pretty sparse, not sure what I'm doing wrong.
Upvotes: 8
Views: 13693
Reputation: 4886
It appears that when adding a new coordinate, you need to pass also the dimension along which it's added. So in this case, it would be:
subset.assign_coords(
alternate_sample_weights=('samples', np.zeros(5)))
Upvotes: 5