user308827
user308827

Reputation: 21981

Subset netCDF in python based on another variable

I have a netCDF file where I want to replace some data based on another variable in the netCDF file. The file is available here: https://umd.box.com/s/lrb12vl7bxbqpv2lt0c27t8m0ps0nm0e and has the following structure:

  dimensions:
    lat = 720;
    time = 3;
    lon = 1440;
  variables:
    float cntry_codes(lat=720, lon=1440);
      :_FillValue = 0.0f; // float

float data(time=3, lat=720, lon=1440);
  :_FillValue = NaNf; // float
  :units = "%";

int time(time=3);

float longitude(lon=1440);

float latitude(lat=720);

I want to replace the 'data' values in the grid cells (where the cntry_codes value is 840) to a new value of 0.8. I am trying to subset like this:

import netCDF4
lat_inds = numpy.where(cntry_codes = 840.0)
lon_inds = numpy.where(cntry_codes = 840.0)

However, this just does not work. Any better solution?

Upvotes: 0

Views: 1266

Answers (1)

kikocorreoso
kikocorreoso

Reputation: 4219

Try the following:

import netCDF4 as nc

dataset = nc.Dataset('/path/to/data.nc', 'r+')

cntry = dataset.variables['cntry_codes'][:]
shape = dataset.variables['data'].shape

for i in range(shape[0]):
    data_i = dataset.variables['data'][i]
    data_i[cntry == 840.0] = 0.8
    dataset.variables['data'][i] = data_i

dataset.close()

Now, your data.nc file should be updated with the new info. Tell me if it helps.

The docs for the netCDF4-python library are here.

Upvotes: 2

Related Questions