1

I am trying to rename a variable in some netcdf files. I am able to accomplish this using xr.Dataset.rename(). However, when I write that out to a netcdf file it has the old variable name that I was trying to replace. Here is the output from the original:

xr.open_dataset('/Volumes/Ext HDD 1/Python_data/crop_means/argentinacorn_tp_mean.nc')

enter image description here

#rename and save files
import glob
import xarray as xr
precip_files=glob.glob('/Volumes/Ext HDD 1/Python_data/crop_means/*tp*.nc')

for i in precip_files:

    data=xr.open_dataset(i)
    data2=data.rename_vars(name_dict={'tp_mean':'total_precip'})
    data2.to_netcdf('/Volumes/Ext HDD 1/Python_data/crop_means2/'+i.split('/')[-1].split('_'). 
    [0]+'_total_precip_mean.nc')

When loading in one of the new files this is the output:

xr.open_dataset('/Volumes/Ext HDD 1/Python_data/crop_means2/argentinacorn_total_precip_mean.nc')

enter image description here

They are exactly the same. If I just run the code without writing it out, this is what outputs:

data=xr.open_dataset('/Volumes/Ext HDD 1/Python_data/crop_means/argentinacorn_tp_mean.nc')
data=data.rename_vars(name_dict={'tp_mean':'total_precip'})

enter image description here

1 Answer 1

3

Using data.rename instead of data.rename_vars will solve this issue.

    data2=data.rename(name_dict={'tp_mean':'total_precip'})
    data2.to_netcdf(...)
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.