Python tools

This example shows how you can use Python to work with SILO’s NetCDF files.

Software requirements

Python 3 is used in these examples. You will also need these Python packages:

Region mask

The example will compute the mean annual rainfall for Queensland. To process data for a specific region, you must provide a NetCDF mask file with the same geometry as the data file(s). If you already have a mask file in another format, you may be able to convert it to NetCDF format using GDAL.

You can download an example mask file for Queensland here (NC, 573KB) .

Scripts

The script below calculates a regional mean using SILO’s monthly rainfall rasters. To compute the mean:

  1. Download all the monthly datafiles. The example uses data from 1961-1990. The data can be downloaded using a variety of methods.
  2. Create a mask file for the region of interest, or use our example mask (NC, 573KB).
  3. Run the Python script below.
import numpy
import netCDF4

# Load the regional mask
with netCDF4.Dataset('mask_qld.nc', 'r') as mask_dataset:
    mask_data = mask_dataset.variables['mask'][:]

# Initialise the results list
results = []

# Loop over years
for year in range(1961, 1990):
    # Load the monthly rainfall data for all months in the year
    with netCDF4.Dataset('{:d}.monthly_rain.nc'.format(year), 'r') as dataset:
        data = dataset.variables['monthly_rain'][:]
        # Apply regional mask to the data
        data.mask = mask_data.mask
        # Calculate the annual regional average rainfall
        # by computing the average across all months
        # and all grid points within the mask
        average = numpy.mean(data)
    # Append result to the list
    results.append(average)

# Output the annual average rainfall for all years
print(results)
Licence
Creative Commons Attribution 4.0 International (CC BY 4.0) ( http://creativecommons.org/licenses/by/4.0/ )
Last updated
18 Sep 2017