简体   繁体   中英

add new coordinates to an xarray.DataArray

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.

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM