python - 如何将 numpy 数组创建为 xarray 数据数组?

标签 python numpy jupyter python-xarray

我正在尝试将 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 数据数组?

最佳答案

您不需要提供坐标列表,字典就足够了:

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

关于python - 如何将 numpy 数组创建为 xarray 数据数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70319614/

相关文章:

python - 具有 apache 和 mod_wsgi 的多个 django 站点

python - Pytorch XOR 实现舍入问题?

python - python 中的可变对象和常量

python - 随机矩阵 : int() argument must be a string or a number, 不是 'tuple'

python - 如何检查矩阵中的行是否有重复项?

python - 改进 Numpy 中的矩阵乘法

在任意位置插入列的 Pythonic 方式

python - 如何验证 Jupyter nbextension 的安装

python - 是否可以在没有轴的情况下向绘图添加另一个值?

python - 如果就地修改列表,Traitlet 列表将不会运行回调