0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PythonでNetCDF形式のデータを扱う

Posted at

#環境
Ubuntu18.04LTS
Python3

#環境構築
Python3でNetCDF形式のファイルを使用するためにはNetCDF4モジュールが必要。
このモジュールはpip3で簡単にインストールできた。

#PythonでNetCDFファイルのI/O
以下は緯度、経度、時間の三次元変数T2が格納されたNetCDFファイルを開いて、新たに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

0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?