2

I have two netCDF files: file1.nc and file2.nc The only difference is that file1.nc contains one variable 'rho' which I want to append to file2.nc but by modifying the variables. The original file2.nc does not contain 'rho' in it. I am using Python module netCDF4.

import netCDF4 as ncd  
file1data=ncd.Dataset('file1.nc')

file1data.variables['rho']

<class 'netCDF4._netCDF4.Variable'> float64 rho(ocean_time, s_rho, eta_rho, xi_rho)
    long_name: density anomaly
    units: kilogram meter-3
    time: ocean_time
    grid: grid
    location: face
    coordinates: lon_rho lat_rho s_rho ocean_time
    field: density, scalar, series
    _FillValue: 1e+37 
unlimited dimensions: ocean_time 
current shape = (2, 15, 1100, 1000) 
filling on

So rho has shape of [2,15,1100,1000] but while adding to file2.nc, I only want to add rho[1,15,1100,1000] i.e. only the data of the second time step. This will result in 'rho' in file2.nc being of shape [15,1100,1000]. But I have been unable to do so.

I have been trying code like this:

file1data=ncd.Dataset('file1.nc')
rho2=file1data.variables['rho']
file2data=ncd.Dataset('file2.nc','r+') # I also tried with 'w' option; it does not work
file2data.createVariable('rho','float64')
file2data.variables['rho']=rho2  # to copy rho2's attributes
file2data.variables['rho'][:]=rho2[-1,15,1100,1000] # to modify rho's shape in file2.nc
file2data.close()

What am I missing here?

2
  • sorry I meant: So rho has shape of [2,15,1100,1000] but while adding to file2.nc, I only want to add rho[1, :, :, :] i.e. only the data of the second time step. Commented Jan 14, 2019 at 22:48
  • What are the variables and dimensions in the second file? Are they the same with file1? If in file2, you have array shaped [15,1100,1000], you should squeeze (use module NumPy) the dimensions i.e import numpy as np;file2data.variables['rho'][:]=np.squeeze(rho2[-1,15,1100,1000]) Commented Jan 15, 2019 at 10:30

1 Answer 1

1

You have not specified the size of variable rho in your second netCDF file.

What you are doing is:

file2data.createVariable('rho','float64')

while it is supposed to be

file2data.createVariable('rho','float64',('ocean_time', 's_rho', 'eta_rho', 'xi_rho'))
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.