2

I'm working with ERA-Interim data from ECMWF, where the variables I need are spread over multiple files. How can I add a variable from one file to an existing file so that, in the end, I have one file with all the variables I need?

I've tried the append(), concatenate() and merge functions so far and nothing has worked.

p_data = anapath1+'/'+yyyy+'/'+mm+'/'+'P'+date 
b_data = anapath1+'/'+yyyy+'/'+mm+'/'+'B'+date 
g_data = anapath1+'/'+yyyy+'/'+mm+'/'+'G'+date 


 #Open/Read netCDF files
 inpcst = xr.open_dataset(cstfile)
 inp1 = xr.open_dataset(p_data)
 inp2 = xr.open_dataset(b_data)
 inp3 = xr.open_dataset(g_data)

These are some of the data files that I'm using. I loaded them into python.

  cdo merge inp1 inp2 inp 

I tried this method to combine two data files but get the following error:

  File "<ipython-input-12-667af80d1ae4>", line 49
     cdo merge inp1 inp2 inp
              ^
   SyntaxError: invalid syntax

I've seen this code exactly like that on here before, so I don't know why there is a syntax error. It's very easy in Matlab since you can just do this:

  inp = inp1
  inp.a = inp2.a
  inp.b = inp3.b   

where a and b are the variables from inp2 and inp3 that I want to add to inp

I simply want to copy certain variables from one file to another

ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86
Joey Bard
  • 21
  • 1
  • 3

1 Answers1

0

welcome to SO, If you are new to NETCDF handling I strongly suggest you use the command line operators of CDO and NCO to do this kind of task... For example you can select a specific variable from a file and put it in its own file like this:

cdo selvar,varname in.nc out.nc 

and you can then cat files together to create one combined file like this:

cdo cat file1.nc file2.nc cat_file.nc

and then there are a whole bunch of operators in both packages to perform time averages, means, maxes, percentiles etc etc...

check out the documentation here: https://code.mpimet.mpg.de/projects/cdo/wiki/Cdo#Documentation

If you are on linux ubuntu or mint you can install it simply:

cdo apt-get install cdo

ncrcat can also cat together netcdf files, see here for details: https://linux.die.net/man/1/ncrcat

ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86