我有一个数据数组 (1500 x 2500),我想将其写入 netcdf 文件,但纬度/经度网格的间距不规则。我可以创建一个包含数据的 netcdf 文件,但该文件似乎不可读和/或格式不正确。例如,当我尝试使用 NOAA 天气和气候工具包读取它时,我收到一条错误,指出该文件被扫描为“网格”文件,但未找到网格。这是我的代码:
from netCDF4 import Dataset
ndvi_nc = Dataset("ndvi_out.nc", "w", format="NETCDF4")
print(ndvi_nc.data_model)
time = ndvi_nc.createDimension("time", 1)
lat = ndvi_nc.createDimension("lat", 3750000)
lon = ndvi_nc.createDimension("lon", 3750000)
data = ndvi_nc.createDimension("data", 3750000)
print(lats.shape)
print(lons.shape)
print(NDVInew.shape)
times = ndvi_nc.createVariable("time","f8",("time",))
latitudes = ndvi_nc.createVariable("lat","f4",("lat",))
longitudes = ndvi_nc.createVariable("lon","f4",("lon",))
ndvi = ndvi_nc.createVariable("ndvi","f4",("data",))
ndvi_nc.description = "NDVI dataset"
ndvi_nc.source = "netCDF4 python module tutorial"
latitudes.units = "degrees north"
longitudes.units = "degrees west"
ndvi.units = "dimensionless"
times.units = "seconds since 1970-1-1"
flatlats = lats.flatten()
flatlons = lons.flatten()
flatndvi = NDVInew.flatten()
print(flatndvi.shape)
latitudes[:] = flatlats
longitudes[:] = flatlons
ndvi[:] = flatndvi
times = 1303939211
print(ndvi)
print(latitudes)
print(longitudes)
ndvi_nc.close()
这是输出:
NETCDF4
(1500, 2500)
(1500, 2500)
(1500, 2500)
(3750000,)
<class 'netCDF4._netCDF4.Variable'>
float32 ndvi(data)
units: dimensionless
unlimited dimensions:
current shape = (3750000,)
filling on, default _FillValue of 9.969209968386869e+36 used
<class 'netCDF4._netCDF4.Variable'>
float32 lat(lat)
units: degrees north
unlimited dimensions:
current shape = (3750000,)
filling on, default _FillValue of 9.969209968386869e+36 used
<class 'netCDF4._netCDF4.Variable'>
float32 lon(lon)
units: degrees west
unlimited dimensions:
current shape = (3750000,)
filling on, default _FillValue of 9.969209968386869e+36 used
是否有更好的方法将数据写入 netcdf?
谢谢
--马特
最佳答案
您不需要展平所有内容,可以直接将间距不均匀的网格写入 netCDF。您创建两个维度 x/y,然后 lon
、lat
和 ndvi
都是这些维度上的 2D 字段。所以这样的事情对我有用:
from netCDF4 import Dataset
ndvi_nc = Dataset("ndvi.nc", "w")
lats = np.random.rand(1500, 2500)
lons = np.random.rand(1500, 2500)
NDVInew = np.random.rand(1500, 2500)
time = ndvi_nc.createDimension("time", 1)
lat = ndvi_nc.createDimension("y", 1500)
lon = ndvi_nc.createDimension("x", 2500)
times = ndvi_nc.createVariable("time", "f8", ("time",))
latitudes = ndvi_nc.createVariable("lat", "f4", ("y", "x"))
longitudes = ndvi_nc.createVariable("lon", "f4", ("y", "x"))
ndvi = ndvi_nc.createVariable("ndvi", "f4", ("y", "x"))
ndvi_nc.description = "NDVI dataset"
ndvi_nc.source = "netCDF4 python module tutorial"
latitudes.units = "degrees north"
longitudes.units = "degrees west"
ndvi.units = "dimensionless"
times.units = "seconds since 1970-1-1"
flatlats = lats.flatten()
flatlons = lons.flatten()
flatndvi = NDVInew.flatten()
latitudes[:] = lats
longitudes[:] = lons
ndvi[:] = NDVInew
times[:] = 1303939211
ndvi_nc.close()
关于python - 使用 python 将不规则间隔的地理引用二维数组写入 netcdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61002164/