简体   繁体   English

写入 netcdf 时重命名 xarray 变量恢复为旧变量

[英]Renaming xarray variable reverts to old variable when writing to netcdf

I am trying to rename a variable in some netcdf files.我正在尝试重命名某些 netcdf 文件中的变量。 I am able to accomplish this using xr.Dataset.rename() .我可以使用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.但是,当我将其写入 netcdf 文件时,它具有我试图替换的旧变量名。 Here is the output from the original:这是原始的 output:

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

在此处输入图像描述

#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:当加载其中一个新文件时,这是 output:

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

在此处输入图像描述

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'})

在此处输入图像描述

Using data.rename instead of data.rename_vars will solve this issue.使用data.rename代替data.rename_vars将解决这个问题。

    data2=data.rename(name_dict={'tp_mean':'total_precip'})
    data2.to_netcdf(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM