Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add numpy array as variable to Xarray Dataset

This seems like a very basic operation, but I can't figure out how to do it using the xarray documentation.

I have an xarray DataSet:

dss
<xarray.DataArray (y: 1000, x: 1334)>
dask.array<shape=(1000, 1334), dtype=uint8, chunksize=(222, 58)>
Coordinates:
    band     int32 1
  * y        (y) float64 2.218e+06 2.218e+06 2.218e+06 2.218e+06 2.218e+06 ...
  * x        (x) float64 1.891e+06 1.891e+06 1.891e+06 1.891e+06 1.891e+06 ...
Attributes:
    transform:   (30.0, 0.0, -2493045.0, 0.0, -30.0, 3310005.0, 0.0, 0.0, 1.0)
    crs:         +ellps=GRS80 +lat_0=23 +lat_1=29.5 +lat_2=45.5 +lon_0=-96 +n...
    res:         (30.0, 30.0)
    is_tiled:    1
    nodatavals:  (nan,)

and a numpy array with the correct dimensions:

print(np.shape(nmap))
(1000, 1334)
nmap
array([[ 0.15,  0.1 ,  0.15, ...,  0.05,  0.05,  0.02],
       [ 0.15,  0.1 ,  0.05, ...,  0.05,  0.05,  0.05],
       [ 0.1 ,  0.15,  0.15, ...,  0.05,  0.05,  0.02],
       ..., 
       [ 0.02,  0.02,  0.02, ...,  0.02,  0.02,  0.02],
       [ 0.02,  0.09,  0.09, ...,  0.02,  0.02,  0.02],
       [ 0.02,  0.09,  0.09, ...,  0.02,  0.02,  0.02]])

I would like to add the array to the DataSet. My ultimate goal is to do spatial interpolation using x and y to extract interpolated values of nmap on a new grid.

like image 205
Chris Sherwood Avatar asked Jul 05 '18 16:07

Chris Sherwood


People also ask

What is xarray Dataset?

Xarray is an open-source Python package for working with labeled multi-dimensional datasets.

What are coordinates in Xarray?

coords : a dict-like container of arrays (coordinates) that label each point (e.g., 1-dimensional arrays of numbers, datetime objects or strings)

How do I drop a dimension in Xarray?

In future versions of xarray (v0. 9 and later), you will be able to drop coordinates when indexing by writing drop=True , e.g., ds['bar']. sel(x=1, drop=True) .


1 Answers

Do you want to create a Dataset that contains your numpy array nmap? Or do you want to make an arithmetic dss + nmap?

For the former case, you need to make a Dataset from dss first and assign nmap to it, as your dss is not a Dataset but a DataArray.

To make a Dataset from DataArrays, you can pass a dictionary mapping the array name to the DataArray object. If your array is not a DataArray but a numpy array or dask array, you need a tuple (dimensions, array, [attribute]).

ds = xr.Dataset({'dss': dss, 'nmap': (('y', 'x'), nmap)})

Or another way to do the same thing is

ds = xr.Dataset({})
ds['dss'] = ds
ds['nmap'] = (('y', 'x'), nmap)

For the latter case, simply do

dss + nmap
like image 133
Keisuke FUJII Avatar answered Sep 25 '22 01:09

Keisuke FUJII