`i want to clip netcdf with shapefile and keep getting errors. i also tried to project it to the same coordinate system, but seems not working. Can you please help me?
import xarray
import geopandas
from shapely.geometry import mapping
import glob
# File paths
shapefile = 'Basin.shp'
netcdf_pattern = r"C:Surface runoffqtot_new.nc"
# Find matching netCDF files
file_list = sorted(glob.glob(netcdf_pattern))
if not file_list:
print("No netCDF files found matching the pattern:", netcdf_pattern)
else:
print("Found the following netCDF files:")
for file in file_list:
print(file)
# Read shapefile
sf = geopandas.read_file(shapefile)
# Set CRS for shapefile
sf.set_crs('epsg:4326', inplace=True, allow_override=True)
for file in file_list:
# Open netCDF file using the 'netcdf4' engine
nc_file = xarray.open_dataset(file, engine='netcdf4')
# Set CRS for netCDF files
nc_file.rio.write_crs('epsg:4326', inplace=True)`your text`
# Clip netCDF file using latitude and longitude
clipped_nc = nc_file.rio.clip(sf.geometry.apply(mapping), sf.crs, all_touched=True)`
New contributor
Natnael Shiferaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.