参考:How to convert NetCDF to GeoTIFF?
参考:利用Python(netCDF4库)读取.nc文件(NetCDF气象数据文件)的基本操作
参考:经度转换0°-360°与-180°-180°之间的相互转换
参考:https://blog.csdn.net/weixin_44237337/article/details/119707332
NetCDF TO GeoTIFF
# The first step is to import the packages:
# packages
import xarray as xr
import rioxarray as rio
# The xarray package enables to load and open the NetCDF file to convert:
nc_file = xr.open_dataset('./mydirectory/medsea_tem_20200320_21.nc')
nc_file
# The next step is to extract the variable of your choice to convert into raster file.
# We want here the bottom temperature bottomT:
bT = nc_file['bottomT']
# It is suggested to provide spatial axis x and y for the GeoTIFF and check for Coordinate Reference System (CRS). No output is required:
bT = bT.rio.set_spatial_dims(x_dim='lon', y_dim='lat')
bT.rio.crs
# Copernicus Marine products have as standard CRS - the WGS 84 (EPSG 4326) - except for ARCTIC products. This projection system can be defined as follows:
# Define the CRS projection
bT.rio.write_crs("epsg:4326", inplace=True)
# Finally, save the GeoTIFF file:
bT.rio.to_raster(r"medsea_bottomT_raster.tiff")
经度转换0°-360°与-180°-180°之间的相互转换
0°-360°转换为-180°-180°
da1 = xr.open_dataset('file.nc') # 文件中坐标标签为‘longitude'
da1['lon'] = xr.where(da1['longitude'] > 180, da1['longitude'] - 360, da1['longitude'])
da1 = (da1
.swap_dims({'longitude': 'lon'})
.sel(**{'lon': sorted(da1.lon)})
.drop('longitude'))
da1 = da1.rename({'lon': 'longitude'})
-180°-180°转换为 0°-360°
da = xr.open_dataset("file.nc", engine="netcdf4")
lon_name = 'lon'
da['longitude'] = xr.where(da[lon_name] < 0, da[lon_name]+360, da[lon_name])
da = (da
.swap_dims({lon_name: 'longitude'})
.sel(**{'longitude': sorted(da.longitude)})
.drop(lon_name))
da = da.rename({'longitude': lon_name})