如何使用Python创建NetCDF文件

之前介绍过如何使用Python处理NetCDF格式文件,这次介绍一下如何创建NetCDF文件。

使用netcdf4-python创建netCDF格式文件通常按照如下流程:

  1. 打开/创建netCDF文件对象

  2. 定义数据维度

  3. 基于定义的维度创建变量

  4. 存储数据到变量

  5. 为变量和数据集添加属性

  6. 关闭文件对象

示例代码如下:

from datetime import datetime

import numpy as np
import pandas as pd

import netCDF4 as nc


##create NetCDF file
newfile = nc.Dataset('newfile.nc', 'w', format='NETCDF4')

##define dimesions
long = newfile.createDimension('longitude', size=360)
lati = newfile.createDimension('latitude', size=180)
heights = newfile.createDimension('height', size=15)
times = newfile.createDimension('time', size=None)

##define variables for storing data
lon = newfile.createVariable('lon', 'f4', dimensions='longitude')
lat = newfile.createVariable('lat', 'f4', dimensions='latitude')
height = newfile.createVariable('height', 'f4', dimensions='height')
time = newfile.createVariable('times', 'S19', dimensions='time')
temps = newfile.createVariable('temperature', 'f4', dimensions=('longitude', 'latitude', 'height', 'time'))

##generate random values
temp = np.random.randint(-40, 40, size=(360, 180, 15, 24))

date_range = pd.date_range(datetime(2019, 6, 1, 0), datetime(2019, 6, 1, 23), freq='1h')

##add data to variables
lon[:] = np.arange(-180, 180)
lat[:] = np.arange(-90, 90)
height[:] = [10, 50, 100, 150, 200, 500, 1000, 1500, 2000, 3000, 4000, 5000, 6000, 8000, 10000]
temps[...] = temp
for i in range(24):
    time[i] = date_range[i].strftime('%Y-%m-%d %H:%M:%S')

##add attributes    
#add global attributes
newfile.title = 'Example of create NetCDF file using netcdf4-python'
newfile.start_time = time[i]
newfile.times = time.shape[0]
newfile.history = 'Created ' + datetime(2019, 6, 1, 0, 0, 0).strftime('%Y-%m-%d %H:%M%S')

#add local attributes to variable
lon.description = 'longitude, west is negative'
lon.units = 'degrees east'

lat.description = 'latitude, south is negative'
lat.units = 'degrees north'

time.description = 'time, unlimited dimension'
time.units = 'times since {0:s}'.format(time[0])

temps.description = 'temperature, random value generated by numpy'
temps.units = 'degree'

height.description = 'height, above ground level'
height.units = 'meters'    

##close file
newfile.close()

创建文件
创建nc文件和读取操作使用相同的命令 Dateset,只需要更改mode为w或者a,w表示写,a表示添加。然后需要指定文件的格式format,目前netCDF4-python支持以下格式:NETCDF3_CLASSIC, NETCDF3_64BIT_OFFSET, NETCDF3_64BIT_DATA, NETCDF4_CLASSIC 和 NETCDF4。

NETCDF3_CLASSIC是最初netCDF库所支持的格式,缺陷是文件大小不能超过2G,之后的格式没有此限制。NETCDF4_CLASSIC和NETCDF4格式支持HDF5,能够读取HDF5的库也可以处理这两种格式。

选择文件格式的时候需要注意上述的一些问题。更多的细节见官方文档。

定义维度
因为存储变量的大小取决于其对应的维度,而且变量存储也以维度为界定,所以要先定义维度。维度定义通过.createDimension方法实现。

定义维度时需要注意:netCDF格式文件中存在一个特殊维度:记录维度(record dimension)/无限维度(unlimited dimension),通常是无限大小的,这与常规的经纬度等维度不同。通常时间维度为记录维度,是可以不断增加的。

上述示例中的时间维即为记录维度。通过.isunlimited方法可判断维度是否为记录维度。

定义变量
使用.createVariable方法可以创建变量,只需要给定变量名称,变量类型,变量维度等信息即可。也可以指定一些额外选项对数据进行压缩(精度要求不高/存储空间有限的情况下)。

目前支持的数据类型包括:f4(32位浮点数),f8(64位浮点数),i4(32位符号整型),i2(16位符号整型),i8(64位符号整型),i1(8位符号整型),u1(8位无符号整型),u2(16位无符号整型),u4(32位无符号整型),u8(64位无符号整型),S1(单字符字符串)。对应的旧文件格式数据类型为:f,d,h,s,b,B,c,i,l。

定义变量时可以定义单个变量或者使用组的形式定义变量,单个变量的定义只需要给定变量名即可,如上例所示。如果以组的形式定义变量,可使用类似linux路径的形式指定:/WRF/Variables/temperature,/Chem/Variables/PM2.5,CMAQ/Variables/PM2.5等形式。

更多细节见官方文档。

添加数据
添加数据没什么可说的,按照定义的变量和维度将对应的数据添加到对应变量即可。注意变量维度和数据类型。

添加属性
添加属性时分为全局属性和变量属性。全局属性是对应整个文件的属性,顾名思义,变量属性就是对应每个变量的属性。

在创建nc文件时,属性是可选的。但是为了更为明确的表述文件和变量的信息通常要添加属性,也建议添加属性。

上述所有操作完成后,即可关闭打开的文件对象,完成文件的写入操作。更多函数和方法细节和高级操作见官方文档。

  • 8
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值