原始矩阵是一个1440*720的二维矩阵,以这个为例子来制作。顺便接上一篇CMORPH数据处理。用一个1440*720的降水矩阵来制作。
代码都有注释,把目录换成自己的就可使用。制作nc文件可分为4大步:1:创造维度 2:建立变量 3:给变量赋值 4:增加全局参数
import numpy as np
import os
# ----------------------------------------------------用户输入
path = 'F:/mytest/' # 输入文件路径
index = 'EOD' # 文件的开头几个字符,以免遍历了多余的文件,需根据自己的文件输入
outpath = 'F:/mytest ' # nc文件输出目录
#---------------------------------------------------------
files = [f for f in os.listdir(path) if f.startswith(index)] # 遍历文件夹的数据
for file in files:
with open(path+file, 'rb') as f: # 用with open 打开文件
a = np.fromfile(f, dtype=np.float32) # 把二进制文件转为可读的数字
a = np.reshape(a,(1440,720),order = 'F') # rashape成1440*720的矩阵/根据自己的情况而定
#a = a[::-1]# 翻转矩阵
a[a==-999] =np.nan # 替换-999为空
a = a*24 # mm/hr to mm/day
# -------------------------准备好数据后,开始写入nc文件-----------------------------------------
from netCDF4 import Dataset # 导入nc模块
dataset = Dataset(outpath+file+'.nc', 'w', format='NETCDF4_CLASSIC') # 生成一个空的nc文件
#----------------------------------------------建造维度
lat = dataset.createDimension('lat', 720)
lon = dataset.createDimension('lon', 1440)
precipitation = dataset.createDimension('precipitation',1036800) # 降水1440*720=1036800
# time = dataset.createDimension('time', None) # 可根据需要放入时间,这里先不放入
latitudes = dataset.createVariable('latitude', np.float32, ('lat',)) # 定义变量
longitudes = dataset.createVariable('longitude', np.float32, ('lon',)) #定义变量
# times = dataset.createVariable('time', np.float64, ('time',)) # 定义变量
precipitation = dataset.createVariable('precipitation', np.float32, ('lat','lon')) # 放入变量
# ------------------变量参数
latitudes.units = 'from -89.875' # 变量的单位,这里不是标准写法,只是为了方便提醒
longitudes.units = 'from 0.125'
# times.units = 'hours since 0001-01-01 00:00:00' # 时间单位
# times.calendar = 'gregorian'
precipitation.units = 'mm'
lats = np.arange(-89.875,89.875+0.25, 0.25) # 按照文件给的规则创建经纬度矩阵
lons = np.arange(0.125,359.875+0.25, 0.25)
latitudes[:] = lats # 放入变量
longitudes[:] = lons # 放入变量
precipitation[:,:] = a # 放入变量
# ---------------------输入时间变量,根据情况自己选择是否加入时间。
# from numpy.random import uniform
# nlats = len(dataset.dimensions['lat'])
# nlons = len(dataset.dimensions['lon'])
# precipitation[0:1, :, :] = uniform(size=(1,nlats,nlons)) # 创造时间维度
#
#
#
# from datetime import datetime, timedelta
# from netCDF4 import num2date, date2num
#
# dates = []
# for n in range(times.shape[0]):
# dates.append(datetime(1998, 1, 1) + n * timedelta(hours=24))
# times = date2num(dates, units = times.units, calendar=times.calendar)