Ubuntu18.04LTS Python3
Le module NetCDF4 est requis pour utiliser les fichiers au format NetCDF dans Python3. Ce module était facile à installer avec pip3.
Voici un programme qui ouvre un fichier NetCDF qui stocke les variables tridimensionnelles T2 de latitude, longitude et heure, et crée un nouveau fichier appelé test_ncout.nc.
#coding: utf-8
# This is a sample program to read and write s netCDF file with Python3
from netCDF4 import Dataset
import numpy as np
#*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
#read netCDF file
#*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
#open a netCDF file to read
ifile = "test.nc"
ncin = Dataset(ifile, 'r')
#check
#print(ncin.file_format)
#get variables
#print(ncin.variables.keys())
#get axis data
tin = ncin.variables['time']
latin = ncin.variables['lat']
lonin = ncin.variables['lon']
#get length of axis data
ntime = len(tin)
nlat = len(latin)
nlon = len(lonin)
#check axis
#print(tim[:])
#print(latin[:])
#print(lonin[:])
#read data
vin = ncin.variables['T2']
#check data
#print(vin[:,:,:,:])
#*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
#write netCDF file
#*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
#open a netCDF file to write
ncout = Dataset('test_ncout.nc', 'w', format="NETCDF4")
#check file format
#print(ncout.file_format)
#define axix size
ncout.createDimension('time',ntime)
ncout.createDimension('lat', nlat)
ncout.createDimension('lon', nlon)
#create time axis
time = ncout.createVariable('time', np.dtype('f4').char, ('time'))
time.long_name = 'time'
time.units = 'months since 1850-1-1'
time.axis = 'T'
#create lat axis
lat = ncout.createVariable('lat', np.dtype('f4').char, ('lat'))
lat.long_name = 'latitude'
lat.units ='degrees_north'
lat.axis = 'Y'
#create lon axis
lon = ncout.createVariable('lon', np.dtype('f8').char, ('lon'))
lon.long_name = 'longitude'
lon.units = 'degrees_east'
lon.axis = 'X'
#create variable arry
vout = ncout.createVariable('T2', np.dtype('f4').char, ('time', 'lat', 'lon'))
vout.long_name = '2m temperature'
vout.units = 'K'
#copy axis from original data
time[:] = tin[:]
lon[:] = lonin[:]
lat[:] = latin[:]
vout[:] = vin[:]
ncin.close()
ncout.close()
http://unidata.github.io/netcdf4-python/ https://github.com/Unidata/netcdf4-python
Recommended Posts