我想向现有的 NetCDF 气候数据文件集添加一个包含儒略日期的附加变量。 我已经完成了一些 python 脚本,但是已经有一段时间了,所以我很生疏。阅读“netCDF4 模块”文档后,我尝试编写脚本以使用以下方法创建新变量:
newvarJD= infile.create.Variable('Julian_Day','i4',
('lon','lat','time'))# attributes, varname,
dtype, dimensions=()
但是当它到达这一行时我得到一个“AttributeError: NetCDF: Attribute not found”:
文件“C:/WinPython64/WinPython-64bit-3.4.4.6Qt5/notebooks/netcfdfill.py”,第 35 行,在 newvarJD= infile.create.Variable('Julian_Day','i4',
所以,我认为需要声明尺寸,所以我更改了代码:
lat_nc = infile.dimensions['lat'] #define dimensions for create.variable
lon_nc = infile.dimensions['lon']
time_nc = infile.dimensions['time']
但现在我收到一个新错误,提示 KeyError: 'lat'
我把我对脚本的尝试包括在内,因为我想我还有几个错误。你能帮我吗?
#**************************
# Access standard libraries
#**************************
from netCDF4 import Dataset
import numpy as np
import os
# Set the input/output directories
wrkDir = 'C:/Netcfd/BCSD/test'
Minifile = wrkDir + '/tasmin'
#***************************
# Add a Julian date variable to all *.nc file in directory
#****************************
inList = os.listdir(Minifile) # List all the files in the 'tasmin'
directory
print(inList)
for fileName in inList: # Step through each file
ifile = fileName
baseName, extension = os.path.splitext(ifile)
if extension == '.nc':
infile = Dataset("ifile", "r+", format="NETCDF4")#append to add
Julian
lat_nc = infile.dimensions['lat'] #define dimensions for
create.variable
lon_nc = infile.dimensions['lon']
time_nc = infile.dimensions['time']
newvarJD= infile.create.Variable('Julian_Day','i4',
('lon_nc','lat_nc','time_nc'))#
varname,dtype, dimensions=()
newvarJD.units= "Days"
newvarJD.long_name = 'Annual Julian Days'
JD = 0 # counter used to set Julian day value
for i in range(len(time_nc)):
JD = JD + 1 # start with Julina Day 1
newvarJD = np.asarray(infile[:,:,:,JD])# write data into the
variable created
print ('New NC dims ->'(infile.shape))
infile.close()
最佳答案
该函数称为 createVariable()
。您的代码应该适用于该修复。
关于python - 使用 Python 将变量添加到现有的 Netcdf4 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43172261/