26
25

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 5 years have passed since last update.

PythonでNetCDFの読み書き

Last updated at Posted at 2013-12-01

NetCDFを扱うときのメモ

ChangeLog

  • 2018/07/04 欠損値の指定方法を追記
  • 2015/09/04 コメント内容の反映,書き込み方法の追記

読み込み

NetCDFはnetCDF4モジュールで読み込めます.
Githubページからダウンロード&インストールするか,
MacならAnaconda、WindowsならPython(x,y)等に標準でついてます.

import netCDF4

nc = netCDF4.Dataset('filename.nc', 'r')
dim = len(nc.dimensions['dimname'])
var = nc.variables['varname'][:]

nc.close()

書き込み

import netCDF4
from numpy import dtype

# オブジェクトを作成し,各次元数を設定します.

nc = netCDF4.Dataset('filename.nc', 'w', format='NETCDF3_CLASSIC')
nc.createDimension('ntime', len(time_out))  # e.g. time_out = [0, 1, ...]
# nc.createDimensions('ntime', None)        # unlimitedにする場合
nc.createDimension('xi', x)                 # e.g. x = 10
nc.createDimension('eta', y)                # e.g. y = 10

# その後,各変数を定義します.
# 以下の例では,時間,緯度,経度,3次元変数を定義します.

time = nc.createVariable('time', dtype('int32').char, ('ntime',))
time.long_name = 'time of test variable'
time.units = 'days since 1968-05-23 00:00:00'

lon = nc.createVariable('lon', dtype('double').char, ('eta', 'xi'))
lon.long_name = 'east longitude'
lon.units = 'degree of east longitude'

lat = nc.createVariable('lat', dtype('double').char, ('eta', 'xi'))
lat.long_name = 'north latitude'
lat.units = 'degree of north latitude'

var = nc.createVariable('varname', dtype('double').char, ('ntime', 'eta', 'xi'))
var.long_name = 'test variable'
var.units = 'unit of test variable'

# 最後に,予め np.ndarray 等で作成しておいた値を代入します.

time[:] = time_out
lon[:,:] = lon_out
lat[:,:] = lat_out
var[:,:,:] = var_out

nc.close()

欠損値の指定方法

特定の値を欠損値扱いにしたい場合,変数作成時にfill_valueを設定してやれば良い.

# -999を欠損値とする場合

var = nc.createVariable('varname', dtype('double').char, ('ntime', 'eta', 'xi'), fill_value=-999)

(2018/07/04追記,Thanks @yutabvb

26
25
7

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
26
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?