如何使用latlong详细信息对netcdf文件进行子集化并重写为新的nc文件?

时间:2018-02-08 10:24:26

标签: python netcdf4

我正在尝试使用latlong对netcdf文件进行子集化。我创建了该文件,但它没有通过 ncdump

打开

我试过这个

from netCDF4 import *
from numpy import *
import time

#Read and subset
nc_file = Dataset('D:\\R_Workspace\\19971207.nc','r')

latbound = [16,20]
longbound = [73,77]

lats = nc_file.variables['Latitude'][:]
lons = nc_file.variables['Longitude'][:]

lat_lb = argmin(abs(lats-latbound[0]))
lat_ub = argmin(abs(lats-latbound[1]))

lon_lb = argmin(abs(lons-longbound[0]))
lon_ub = argmin(abs(lons-longbound[1]))

sm_sub = nc_file.variables['soil_moisture_x'][lon_lb:lon_ub,lat_ub:lat_lb]
lat_sub = nc_file.variables['Latitude'][lat_ub:lat_lb]
lon_sub = nc_file.variables['Longitude'][lon_lb:lon_ub]
nc_file.close()

#write to new file
my_file = Dataset('D:\\R_Workspace\\subset\\19971207.nc','w', format = 'NETCDF4')

my_file.discription = 'SM-TRMM-night_UB-subset'
my_file.history = 'Created on: ' +time.ctime(time.time())

#Dimensions
ldim = lat_lb-lat_ub # getting the no of element
lndim = lon_ub-lon_lb

lon = my_file.createDimension('lon',lndim)
lat = my_file.createDimension('lat',ldim)

#Variables
latitude = my_file.createVariable('Latitude',float32,('lat',))
latitude.units = 'Degree_north'
longitude = my_file.createVariable('Longitude',float32,('lon',))
longitude.units = 'Degree_east'

sm = my_file.createVariable('SM',float32,('lon','lat'),fill_value = -9999.0)
sm.units = 'percent'

#Load values to the variables
latitude[:] = lat_sub
longitude[:] = lon_sub
sm[:] = sm_sub
my_file.close()

代码没有给出任何错误,但创建的nc文件不正确,ncdump也无法打开它。请帮我解决这个问题。感谢您宝贵的时间。

3 个答案:

答案 0 :(得分:0)

我会尝试将全局属性从ncfile复制到myfile

 g_attdict = ncfile.__dict__

...

myfile.setncatts(g_attdict)

答案 1 :(得分:0)

sm_sub是2D:

sm_sub = nc_file.variables['soil_moisture_x'][lon_lb:lon_ub,lat_ub:lat_lb]

您正确地将输出变量sm声明为2D变量(lat x lon):

sm = my_file.createVariable('SM',float32,('lon','lat'),fill_value = -9999.0)

但只写出一维:

sm[:] = sm_sub

因此该行需要更改为:

sm[:,:] = sm_sub[:,:]

答案 2 :(得分:0)

这可以在 Unix 系统上使用我的 nctoolkit (https://nctoolkit.readthedocs.io/en/latest/) 包在几行中完成:

import nctoolkit as nc
ds = nc.open_data("infile.nc")

latbound = [16,20]
longbound = [73,77]

ds.crop(lon = longbound, lat = latbound)
ds.to_nc("outfile.nc")