【问题标题】:How to create a numpy array to an xarray data array?如何为 xarray 数据数组创建一个 numpy 数组?
【发布时间】:2022-01-16 00:53:59
【问题描述】:

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

【问题讨论】:

    标签: python numpy jupyter python-xarray


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!我会将此标记为正确的。我用我的真实数据尝试过(不是 np.random.rand),不幸的是我得到了这个错误:MissingDimensionsError: cannot set variable 'y' with 2-dimensional data without explicit dimension names. Pass a tuple of (dims, data) instead.。你知道那是什么意思吗?谢谢!
    • 您的输入之一是嵌入式列表还是二维数组?
    • 其中一个是 3d 数组,但我认为另外两个 lon_atae、lat_atae 是嵌入式列表。这可能是问题所在,应该将列表转换为数组吗?再次感谢!
    • 它们是数组还是列表?此外,如果列表是嵌入的,您确定长度或lon_atae 与您的数据相符吗?例如你可以试试list(itertools.chain.from_iterable(lon_atae))
    • np.array(lon_atae).ravel(),我真的猜到你的数据了
    猜你喜欢
    • 1970-01-01
    • 2017-03-17
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2017-09-18
    相关资源
    最近更新 更多