Python 如何使用latlong详细信息子集netcdf文件并重写为新的nc文件?
我正在尝试使用latlong来子集netcdf文件。我已经创建了文件,但它不是由ncdump打开的 我试过这样做Python 如何使用latlong详细信息子集netcdf文件并重写为新的nc文件?,python,netcdf4,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['
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也无法打开它。请帮我解决这个问题。感谢您的宝贵时间。我会尝试将全局属性从
ncfile
复制到myfile
g_attdict = ncfile.__dict__
我会尝试将全局属性从
ncfile
复制到myfile
g_attdict = ncfile.__dict__
sm_sub
是2D:
sm_sub = nc_file.variables['soil_moisture_x'][lon_lb:lon_ub,lat_ub:lat_lb]
您在此处正确地将输出变量sm
声明为二维变量(lat x lon):
但仅写出一维:
sm[:] = sm_sub
因此,该行需要更改为:
sm[:,:] = sm_sub[:,:]
sm_sub
是2D:
sm_sub = nc_file.variables['soil_moisture_x'][lon_lb:lon_ub,lat_ub:lat_lb]
您在此处正确地将输出变量sm
声明为二维变量(lat x lon):
但仅写出一维:
sm[:] = sm_sub
因此,该行需要更改为:
sm[:,:] = sm_sub[:,:]
这可以在Unix系统上使用my nctoolkit()包在几行中完成:
这可以在Unix系统上使用my nctoolkit()包在几行中完成: