0

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?

2
  • 1
    The code you provide doesn't work. First you should read your data using data = netCDF4.Dataset(...), then access the variables you need, cntry_codes = data.variables['cntry_codes'][:], then play with them, mask = cntry_codes[cntry_codes = 840.0] and, finally, modify the data you want for the data var in the nc file. Commented Sep 15, 2015 at 20:17
  • thanks @kikocorreoso, It is the final step which is confusing me. I.e. how do I modify the data var based on the masked array? Commented Sep 15, 2015 at 20:23

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.