LoginSignup
2
0

More than 5 years have passed since last update.

Python netCDF4でvariablesの有無を確認する方法

Posted at

複数の、variables属性がバラバラのファイルを操作しなければならなかったので、
その時に使用したコードの一部をメモします。

netCDF サンプルデータ
https://www.unidata.ucar.edu/software/netcdf/examples/sresa1b_ncar_ccsm3-example.nc



1.NetCDFのvariables一覧を取得・表示する方法

import netCDF4
ncFILE='sresa1b_ncar_ccsm3-example.nc'
nc = netCDF4.Dataset(ncFILE,'r')
nc_var = nc.variables.keys()
print(nc_var)

結果

odict_keys(['area', 'lat', 'lat_bnds', 'lon', 'lon_bnds', 'msk_rgn', 'plev', 'pr', 'tas', 'time', 'time_bnds', 'ua'])





2.特定のキーを検索してなんらかの処理をする方法

import netCDF4
ncFILE='sresa1b_ncar_ccsm3-example.nc'
nc = netCDF4.Dataset(ncFILE,'r')
#list()で囲まないと、*1のエラーが出る。
nc_var = list(nc.variables.keys())


if 'tas' in nc_var:
   print(tas + ' is exists')
   #データが存在すれば、ここでなんらかの処理をする
else:
   print('no data')



複数のキーを使用するときは'tas'の部分を変数にして、リストにしてループでもいいですね。




参考サイト
http://www-mete.kugi.kyoto-u.ac.jp/matsuba/python/
https://note.nkmk.me/python-dict-in-values-items/
https://github.com/taehoonlee/tensornets/issues/1 (*1)
https://github.com/taehoonlee/tensornets/commit/985bcb5444f8b9cb3457f587568ee95ce25bc683

2
0
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
2
0