I want to reanme the dimensions of a .nc file, from 'latitude' to 'lat' and from 'longitude to lon', to later be able to combine it with another .nc dataset. This is how my .nc file looks like:
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:
I tired using the following code found here:
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()
But the following error pops up:
KeyError: 'longitude not a valid dimension name'
Any ideas? Thank you!
First, thanks to @user2314737 I figured out that one of the files I was trying to rename was corrupt and the dictionary containing the dimensions was empty. I updated the file and found this simple solution to rename the dimensions:
ds1 = xr.open_dataset("dataset-oc-atl-chl-olci-l3-chl_300m_daily-rt_1637844102280.nc")
ds1
[Out]
<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)
The solution is:
ds1 = ds1.rename({'latitude': 'lat','longitude': 'lon'})
[Out]
<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)