如何为 xarray 数据数组创建一个 numpy 数组?

How to create a numpy array to an xarray data array?

我正在尝试将 3D numpy 数组转换为数据数组,但是我收到一个我无法弄清楚的错误。

我有一个 3D numpy 数组(纬度、经度和时间),我希望将它转换成维度为纬度、经度和时间的 xarray 数据数组。

np.random.rand 只是为了制作一个可重现的 3D 数组示例:

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

如何将此 numpy 数组转换为 xarray 数据数组?

你不需要为coords提供列表,字典就足够了:

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