问题描述
我想创建一个三维数据数组,该数组存储温度数据以及相应的纬度和经度以及时间(以小时为单位)。所以我做了如下编码;
np.random.seed(123)
temperature_3d = 15 + 10 * np.random.randn(24,4,4) # 3-dimensional
lat = np.random.uniform(low=-90,high=90,size=(1,4))
lon = np.random.uniform(low=-180,high=180,4))
# round to two digits after decimal point
temperature_3d = np.around(temperature_3d,decimals=2)
lat,lon = np.around([lat,lon],decimals=2)
date_rng = pd.date_range(start='1/1/2018T01:00',end='1/2/2018',freq='H')
da = xr.DataArray(data=temperature_3d,coords={"lat": (["x","y"],lat),"lon": (["x",lon),"day": date_rng},dims=["x","y","day"])
da
我得到这个错误,
ValueError: conflicting sizes for dimension 'x': length 24 on the data but length 1 on coordinate 'lat'
从维度上讲这是错误的,我可以在不包括时间的情况下进行修复,我的目标是创建一个具有720x40x40尺寸(timexlat,lonxtime)的数据数组。
我也是这类图书馆的新手。因此,我将对您的建议表示赞赏。
解决方法
看起来形状需要正确匹配。
首先,由于您的温度数据的形状为 (24,4,4),
temperature_3d = 15 + 10 * np.random.randn(24,4) # 3-dimensional
您需要将日期放在您的暗处:
da = xr.DataArray(data=temperature_3d,coords={"lat": (["x","y"],lat),"lon": (["x",lon),"day": date_rng},dims=["day","x","y"])
其次,您的纬度和经度坐标具有根据 ["x","y"] 的形状,因此在示例中,您需要一个 4x4 网格来表示每个点的纬度,而另一个 4x4 网格用于表示经度在每个点。为此,我们可以使用 np.meshgrid:
latgrid,longrid = np.meshgrid(lat,lon)
所以,完整:
import numpy as np
import xarray as xa
np.random.seed(123)
temperature_3d = 15 + 10 * np.random.randn(24,4) # 3-dimensional
lat = np.random.uniform(low=-90,high=90,size=(4))
lon = np.random.uniform(low=-180,high=180,size=(4))
# round to two digits after decimal point
temperature_3d = np.around(temperature_3d,decimals=2)
lat,lon = np.around([lat,lon],decimals=2)
latgrid,lon)
date_rng = pd.date_range(start='1/1/2018T01:00',end='1/2/2018',freq='H')
da = xa.DataArray(data=temperature_3d,latgrid),longrid),"y"])
da