Search code examples
pythonnetcdf4

Extract data from NetCDF4 file with regional mask file


I am working on multiple NetCDF4 file and want to extract the monthly_rain values from it. Here is my code:

import numpy
import netCDF4

with netCDF4.Dataset('abc.nc', 'r') as mask_dataset:
    mask_data = mask_dataset.variables['mask'][:]

results = []

for year in range(2010, 2019):
    with netCDF4.Dataset('{:d}.monthly_rain.nc'.format(year), 'r') as dataset:
        data = dataset.variables['monthly_rain'][:]
        data.mask = mask_data.mask

        average = numpy.mean(data)

    results.append(average)

print(results)

The outcome from above code is:

[92.82600598372804, 67.01124693612452, 54.30168356893234, 39.58771623758809, 45.30353874205824, 39.017626997972684, 50.94861235658874, 44.55133832249074, 41.7971056907917]

which is the result I want.

However, I want to extract all the monthly_rain value from the file so that I can do further inspection on the dataset. Are there any method that can allow me do that?


Solution

  • Now I can answer... Just do not calculate averages in the loop, but directly append (masked) "data" to the results, and then do any additional post-processing.