I have created a NetCDF file using xarray in python with this code:
latitude_save = sorted(list(set(copy2_sorted['lat'])))
longitud_save = sorted(list(set(copy2_sorted['lon'])))
time_save = sorted(list(set(copy2_sorted['time'])))
tmp = np.array(copy2_sorted['temp']).reshape(len(time_model), 3, 4)
xrds = xr.Dataset(
coords = dict(time = time_save,
lat = latitude_save,
lon = longitud_save),
data_vars = dict(tas = (['time' , 'lat' , 'lon'], tmp)))
xrds = xrds.rio.write_crs("EPSG:4326", inplace=True)
file_save = 'C:/Users/72541988B/Desktop/Copernicus/SSP1-1.9/Tas/{}_tas3.nc'.format(model)
my_enocding = {'time':{'dtype': 'int32' , '_FillValue': None},
'lat':{'dtype': 'float32' , '_FillValue': None},
'lon':{'dtype': 'float32' , '_FillValue': None},
'tas':{'dtype': 'float32' , '_FillValue': float('nan'),'zlib': False}
}
xrds.to_netcdf(file_save, encoding=my_enocding)
(print('Se ha guardado: {}'.format(model)))
xrds = xr.open_dataset("C:/Users/72541988B/Desktop/Copernicus/SSP1-1.9/Tas/CAMS_CSM_tas7.nc")
I have made sure that the latitud and longitud of the code are well saved, by later oppening the nc file in python again and watching the latitude and longitude values using this:
print(xrds["lat"].values)
41.1265, 41.9565, 42.8
print(xrds["lon"].values)
-3.8875, -2.162 , -0.437 , 1.2875
I get the defined latitudes and longitudes without any problems. But then when I try to open it in QGIS the coordinates are not well loaded, in fact, is as if didi not have any coordinate, since it creates me a grid that extend from 0.0 to 4.0 and from 0.0 to -3.0.
I have tried changing thecoordinates of the nc directly in QGIS but it gives me an error because the coordinates are not defined. I have also tried to define while saving the netCDF file defining the coordinate system EPSG: 4326. But I have the same problem, in python the lecture is okay but in QGIS no.
I have used this code to create a netCDF of precipitation and I had not problems, but when I do the same with the temperature I get this problem when trying to open it in QGIS (because in python everything is okay) so I figure it has something to do with QGIS but I can not tell what. What is it?
1 Answer 1
Had the same issue, had to set a bunch of attributes in xarray before exporting:
xrds["crs"] = xr.DataArray(0, attrs={
"grid_mapping_name": "latitude_longitude",
"epsg_code": "EPSG:4326",
"semi_major_axis": 6378137.0,
"inverse_flattening": 298.257223563
})
xrds['tas'].attrs['grid_mapping'] = 'crs'
xrds['lat'].attrs['standard_name'] = 'latitude'
xrds['lat'].attrs['units'] = 'degrees_north'
xrds['lon'].attrs['standard_name'] = 'longitude'
xrds['lon'].attrs['units'] = 'degrees_east'
xrds = data.rio.write_crs('EPSG:4326')
xrds.attrs["Conventions"] = "CF-1.8"