Home > Mobile >  How to create a numpy array to an xarray data array?
How to create a numpy array to an xarray data array?

Time:12-12

I am trying to convert a 3D numpy array to a data array however I am getting an error that I cannot figure out.

I have a 3D numpy array (lat, lon, and time), and I am hoping to convert it into an xarray data array with the dimensions being lat, lon, and time.

The np.random.rand is just to make a reproducible example of a 3D array:

atae = np.random.rand(10,20,30) # 3d array 
lat_atae = np.random.rand(10) # latitude is the same size as the first axis
lon_atae = np.random.rand(20) # longitude is the same size as second axis
time_atae = np.random.rand(30) # time is the 3rd axis


data_xr = xr.DataArray(atae, coords=[{'y': lat_atae,'x': lon_atae,'time': time_atae}], 
                    dims=["y", "x", "time"])


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-156-8f8f8a1fc7aa> in <module>
----> 1 test = xr.DataArray(atae, coords=[{'y': lat_atae,'x': lon_atae,'time': time_atae}], 
      2                     dims=["y", "x", "time"])
      3 

~/opt/anaconda3/lib/python3.8/site-packages/xarray/core/dataarray.py in __init__(self, data, coords, dims, name, attrs, indexes, fastpath)
    408             data = _check_data_shape(data, coords, dims)
    409             data = as_compatible_data(data)
--> 410             coords, dims = _infer_coords_and_dims(data.shape, coords, dims)
    411             variable = Variable(dims, data, attrs, fastpath=True)
    412             indexes = dict(

~/opt/anaconda3/lib/python3.8/site-packages/xarray/core/dataarray.py in _infer_coords_and_dims(shape, coords, dims)
    104         and len(coords) != len(shape)
    105     ):
--> 106         raise ValueError(
    107             f"coords is not dict-like, but it has {len(coords)} items, "
    108             f"which does not match the {len(shape)} dimensions of the "

ValueError: coords is not dict-like, but it has 1 items, which does not match the 3 dimensions of the data

How do I convert this numpy array into a xarray data array?

CodePudding user response:

You don't need to provide a list for coords, the dictionary is enough :

data_xr = xr.DataArray(atae, 
coords={'y': lat_atae,'x': lon_atae,'time': time_atae}, 
dims=["y", "x", "time"])
  • Related