Blog

  • How to read netcdf file in Python

Netcdf (nc) file format widely used data format in Geo, Earth, and planetary science field. To import nc data to python workspace, we will need to install necdf4 package in python. Depending on your python software tool do a search online on how to install package for that specific python tool. If you are using anaconda3 like me just follow the instructing below:

open Anaconda > Go to Environment > click in search package and write netcdf4 > click check button to install netcdf4 package.

After installing the package open the python terminal (I use spyder/ipython terminal) and follow the script:

from netCDF4 import Dataset as nc #this line imports the package we just installed

file=nc('/Users/afahad/Desktop/slp.mon.mean.nc') # this line defines the file path of the file we are trying to read

#read variable

slp=file.variables['slp'][:] # ":" takes all the data dimension from the file

lon=file.variables['lon'][:]
lat=file.variables['lat'][:]
time=file.variables['time'][:]

To make sure if your data dimensions are right you can type the following commands and check if they match:

slp.shape
lon.shape
lat.shape
time.shape

Install anaconda: https://www.anaconda.com/