Skip to content

Instantly share code, notes, and snippets.

@rohithteja
Last active February 21, 2022 19:20
Show Gist options
  • Select an option

  • Save rohithteja/2cde20b7848ede068ea90b4680ddb09e to your computer and use it in GitHub Desktop.

Select an option

Save rohithteja/2cde20b7848ede068ea90b4680ddb09e to your computer and use it in GitHub Desktop.
Clipping over shapefile
import datetime
import geopandas as gpd
import pandas as pd
import numpy as np
from shapely.geometry import mapping
import rioxarray
# read shapefile
shapefile = gpd.read_file("data/world-administrative-boundaries/world-administrative-boundaries.shp")
# convert into standard CRS
t2m = ds_interp.t2m
t2m.rio.write_crs("epsg:4326", inplace=True)
temp_country = {}
small_countries = []
for i in range(shapefile.shape[0]):
data = shapefile[shapefile.index==i]
try:
clip = t2m.rio.clip(data.geometry.apply(mapping), data.crs).mean(dim=['longitude','latitude']).values
temp_country[shapefile.iloc[i]['iso3']] = clip
except:
small_countries.append(shapefile.iloc[i]['name'])
# date as index
start_time = datetime.datetime(2021, 1, 1, 0, 0, 0)
end_time = datetime.datetime(2021, 12, 31, 23, 0, 0)
idx = pd.date_range(start_time, end_time, freq = '1M')
idx = [i.strftime("%b")+ ' 2021' for i in idx]
# df of temperatures for each country
df_temp = pd.DataFrame(temp_country)
df_temp.index = idx
# convert kelvin into celsius
df_temp = df_temp.applymap(lambda x:x-273.15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment