重命名 netCDF 维度

Rename netCDF dimensions

我想重新设置 .nc 文件的尺寸,从 'latitude' 到 'lat' 和 'longitude to lon',以便以后能够将它与另一个 .nc 数据集组合。这是我的 .nc 文件的样子:

Dimensions:    (time: 1, latitude: 1037, longitude: 1345)
Coordinates:
  * latitude   (latitude) float32 37.7 37.7 37.69 37.69 ... 35.01 35.0 35.0
  * time       (time) datetime64[ns] 2021-11-23
  * longitude  (longitude) float32 -9.001 -8.999 -8.996 ... -5.507 -5.504 -5.501

Data variables:
    CHL        (time, latitude, longitude) float32 ...

Attributes: (12/38)
    FROM_ORIGINAL_FILE__Metadata_Conventions:  Unidata Dataset Discovery v1.0
    keywords:                                  satellite,observation,ocean
    summary:                                   These data are Level-3 satelli...
    history:                                   1637676190 Created by composit...
    netcdf_file_type:                          NETCDF4_CLASSIC
    contact:                                   email: cmems@pml.ac.uk
    ...                                        ...
    start_date:                                2021-11-23
    start_time:                                00:00:00 UTC
    stop_date:                                 2021-11-23
    stop_time:                                 23:59:00 UTC
    _CoordSysBuilder:                          ucar.nc2.dataset.conv.CF1Conve...
    source:      

我厌倦了使用此处找到的以下代码:

from netCDF4 import Dataset
path='dataset-oc-atl-chl-olci-l3-chl_300m_daily-rt_1637778183019.nc'
f=Dataset(path,'r+')
f.renameDimension(u'longitude',u'lon')
f.renameVariable(u'longitude',u'lon')
f.renameDimension(u'latitude',u'lat')
f.renameVariable(u'latitude',u'lat')
f.close()

但是弹出如下错误:

KeyError: 'longitude not a valid dimension name'

有什么想法吗?谢谢!

检查维度 u'longitude' 是否实际存在,方法是打印数据集的维度:

print(f.dimensions)

或打印 f.dimensions 的键,因为它是字典:

print(f.dimensions.keys())

(参见:Dimensions in a netcdf4 file

首先,感谢@user2314737,我发现我试图重命名的文件之一已损坏并且包含维度的字典是空的。我更新了文件并找到了这个重命名维度的简单解决方案:

ds1 = xr.open_dataset("dataset-oc-atl-chl-olci-l3-chl_300m_daily-rt_1637844102280.nc")
ds1

[出局]

<xarray.Dataset>
Dimensions:  (time: 1, latitude: 1037, longitude: 1345)
Coordinates:
  * latitude      (latitude) float32 37.7 37.7 37.69 37.69 37.69 ... 35.01 35.01 35.0 35.0
  * time     (time) datetime64[ns] 2021-11-23
  * longitude      (longitude) float32 -9.001 -8.999 -8.996 -8.993 ... -5.507 -5.504 -5.501
Data variables:
    CHL      (time, lat, lon) float32 ...
Attributes: (12/38)

解决方法是:

ds1 = ds1.rename({'latitude': 'lat','longitude': 'lon'})

[出局]

<xarray.Dataset>
Dimensions:  (time: 1, lat: 1037, lon: 1345)
Coordinates:
  * lat      (lat) float32 37.7 37.7 37.69 37.69 37.69 ... 35.01 35.01 35.0 35.0
  * time     (time) datetime64[ns] 2021-11-23
  * lon      (lon) float32 -9.001 -8.999 -8.996 -8.993 ... -5.507 -5.504 -5.501
Data variables:
    CHL      (time, lat, lon) float32 ...
Attributes: (12/38)

有 NCO ncrename

ncrename -d latitude,lat -d longitude,lon in.nc out.nc