8

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.

1 Answer 1

5

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)))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.