我希望将xarray dataset ds的单个日期和变量ds导出到tif文件中。但是,我的数据数组有太多的维度,我无法理解如何有效地删除维度lsm_time。
ds
<xarray.Dataset>
Dimensions: (time: 2436, y: 28, x: 58, lsm_time: 1)
Coordinates:
* time (time) datetime64[ns] 2015-05-02T12:00:00 ... 2021-12-31T12:...
step <U8 '12:00:00'
surface float64 0.0
* y (y) float64 36.01 36.11 36.21 36.31 ... 38.41 38.51 38.61 38.71
* x (x) float64 -7.64 -7.54 -7.44 -7.34 ... -2.24 -2.14 -2.04 -1.94
spatial_ref int32 0
Dimensions without coordinates: lsm_time
Data variables:
ffmc (time, y, x, lsm_time) float32 nan nan nan ... 88.93 88.53
dmc (time, y, x, lsm_time) float32 nan nan nan ... 6.511 7.908 8.45
dc (time, y, x, lsm_time) float32 nan nan nan ... 406.2 428.5
isi (time, y, x, lsm_time) float32 nan nan nan ... 3.872 3.852
bui (time, y, x, lsm_time) float32 nan nan nan ... 15.08 16.11
fwi (time, y, x, lsm_time) float32 nan nan nan ... 5.303 5.486导出数据数组会引发错误TooManyDimensions。
ds.fwi.sel(time="07-14-2021").rio.to_raster("file_out.tif")
raise TooManyDimensions(
rioxarray.exceptions.TooManyDimensions: Only 2D and 3D data arrays supported. Data variable: fwi在前面的步骤中,我已经删除了维度lsm_time,当我用陆地屏蔽lsm (单一日期)掩蔽dataset ds时,必须复制/添加dataset ds的时间维度。所以这可能是数据处理造成的错误。不过,我可以想办法不戴面具。
lsm
Dimensions: (x: 58, y: 28, time: 1)
Coordinates:
* x (x) float64 -7.64 -7.54 -7.44 -7.34 ... -2.24 -2.14 -2.04 -1.94
* y (y) float64 36.01 36.11 36.21 36.31 ... 38.41 38.51 38.61 38.71
* time (time) datetime64[ns] 2013-11-29
Data variables:
spatial_ref int32 0
lsm (time, y, x) float64 0.0 0.0 0.0 0.0 0.0 ... 1.0 1.0 1.0 0.9996
lsm = lsm.expand_dims({"new_time" : ds.time})
lsm = lsm.rename({"time":"lsm_time"}).rename({"new_time" : "time"}).drop("lsm_time") #issue here: drop_dims removes variable..
ds = ds.where(lsm>=threshold)所以我已经申请了.drop("lsm_time")
但是,它仍然是
print(ds.fwi.sel(time="07-14-2021").dims)
> ('time', 'y', 'x', 'lsm_time')当尝试.drop_dims时,它会删除所有数据变量。
ds.drop_dims('lsm_time')
<xarray.Dataset>
Dimensions: (time: 2436, y: 28, x: 58)
Coordinates:
* time (time) datetime64[ns] 2015-05-02T12:00:00 ... 2021-12-31T12:...
step <U8 '12:00:00'
surface float64 0.0
* y (y) float64 36.01 36.11 36.21 36.31 ... 38.41 38.51 38.61 38.71
* x (x) float64 -7.64 -7.54 -7.44 -7.34 ... -2.24 -2.14 -2.04 -1.94
spatial_ref int32 0
Data variables:
*empty*我错过了什么或者我做错了什么?谢谢你的帮助!
发布于 2022-02-14 18:35:36
尺寸为1的尺寸可以使用.squeeze方法删除。
相反,可以使用.expand_dims添加大小为1的维度。
import xarray as xr
x = xr.tutorial.load_dataset("rasm")
y = x.isel(time=slice(0,1))
y.dims
# Frozen({'time': 1, 'y': 205, 'x': 275})
y.squeeze().dims
# Frozen({'y': 205, 'x': 275})
y.squeeze().expand_dims("newdim").dims
# Frozen({'y': 205, 'x': 275, 'newdim': 1})https://stackoverflow.com/questions/71078885
复制相似问题