Reading and writing NetCDF with Python

Notes on working with NetCDF

ChangeLog --2018/07/04 Added how to specify missing values --2015/09/04 Reflection of comment contents, addition of writing method

Read

NetCDF can be read by the netCDF4 module. Download and install from Github Page, or It comes standard with Anaconda for Mac and Python (x, y) for Windows.

import netCDF4

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

nc.close()

writing

import netCDF4
from numpy import dtype

#Create an object and set each dimension number.

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)        #When setting to unlimited
nc.createDimension('xi', x)                 # e.g. x = 10
nc.createDimension('eta', y)                # e.g. y = 10

#After that, define each variable.
#The following example defines time, latitude, longitude, and 3D variables.

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'

#Finally, np in advance.Substitute the value created by ndarray etc.

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

nc.close()

How to specify missing values

If you want to treat a specific value as a missing value, you can set fill_value when creating the variable.

# -When 999 is a missing value

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

(Added on 2018/07/04, Thanks @yutabvb)

Recommended Posts

Reading and writing NetCDF with Python
Reading and writing CSV with Python
Reading and writing JSON files with Python
Reading and writing fits files with Python (memo)
Example of reading and writing CSV with Python
Python CSV file reading and writing
Reading and writing text in Python
Study from Python Reading and writing Hour9 files
Reading and writing CSV and JSON files in Python
Programming with Python and Tkinter
Python and hardware-Using RS232C with Python-
Draw netCDF file with python
Reading and writing csv files
Reading .txt files with Python
python with pyenv and venv
Works with Python and R
[Introduction for beginners] Reading and writing Python CSV files
Reading, displaying and speeding up gifs with python [OpenCV]
Character code for reading and writing csv files with python ~ windows environment ver ~
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Robot running with Arduino and python
Install Python 2.7.9 and Python 3.4.x with pip.
Neural network with OpenCV 3 and Python 3
Scraping with Node, Ruby and Python
Scraping with Python, Selenium and Chromedriver
Scraping with Python and Beautiful Soup
JSON encoding and decoding with python
Hadoop introduction and MapReduce with Python
[GUI with Python] PyQt5-Drag and drop-
Multi-line size specification reading with python
I played with PyQt5 and Python3
Multiple integrals with Python and Sympy
Coexistence of Python2 and 3 with CircleCI (1.0)
Easy modeling with Blender and Python
Sugoroku game and addition game with python
FM modulation and demodulation with Python
Notes on reading and writing float32 TIFF images in python
uproot: Python / Numpy based library for reading and writing ROOT files
Communicate between Elixir and Python with gRPC
Data pipeline construction with Python and Luigi
Calculate and display standard weight with python
Monitor Mojo outages with Python and Skype
FM modulation and demodulation with Python Part 3
Python installation and package management with pip
Using Python and MeCab with Azure Databricks
POST variously with Python and receive with Flask
Capturing images with Pupil, python and OpenCV
Fractal to make and play with Python
A memo with Python2.7 and Python3 on CentOS
Use PIL and Pillow with Cygwin Python
Create and decrypt Caesar cipher with python
CentOS 6.4 with Python 2.7.3 with Apache with mod_wsgi and Django
Dealing with "years and months" in Python
(Python) HTML reading and regular expression notes
[Easy Python] Reading Excel files with openpyxl
I installed and used Numba with Python3.5
Tweet analysis with Python, Mecab and CaboCha
Linking python and JavaScript with jupyter notebook
Traffic monitoring with Kibana, ElasticSearch and Python
FM modulation and demodulation with Python Part 2