簡體   English   中英

如何將 numpy 數組創建為 xarray 數據數組?

[英]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"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM