[英]mask NetCDF using shapefile and calculate average and anomaly for all polygons within the shapefile
有幾個關於使用 shapefile 屏蔽 NetCDF 和計算平均度量的教程(示例 1 、 示例 2 、 示例 3 )。 但是,我對那些關於屏蔽 NetCDF 和提取平均值等度量的工作流程感到困惑,並且這些教程不包括提取異常(例如,2019 年的溫度與基線平均溫度之間的差異)。
我在這里做一個例子。 我已經下載了 2000 年到 2019 年的月度溫度( 下載溫度文件)和美國州級 shapefile( 下載 shapefile )。 我想根據 2000 年至 2019 年的月平均溫度以及 2019 年相對於 2000 年至 2010 年的基准溫度的溫度異常來獲得州級平均溫度。具體而言,最終的 dataframe 如下所示:
state | 平均溫度 | anom_temp2019 |
---|---|---|
鋁 | xx | xx |
增強現實 | xx | xx |
... | ... | ... |
懷俄明 | xx | xx |
# Load libraries
%matplotlib inline
import regionmask
import numpy as np
import xarray as xr
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
# Read shapefile
us = gpd.read_file('./shp/state_cus.shp')
# Read gridded data
ds = xr.open_mfdataset('./temp/monthly_mean_t2m_*.nc')
......
我非常感謝您提供可以完成上述任務的明確工作流程的幫助。 非常感謝。
這可以使用區域掩碼來實現。 我不使用您的文件,而是使用美國各州的 xarray 教程數據和naturalearth數據。
import numpy as np
import regionmask
import xarray as xr
# load polygons of US states
us_states_50 = regionmask.defined_regions.natural_earth.us_states_50
# load an example dataset
air = xr.tutorial.load_dataset("air_temperature")
# turn into monthly time resolution
air = air.resample(time="M").mean()
# create a mask
mask3D = us_states_50.mask_3D(air)
# latitude weights
wgt = np.cos(np.deg2rad(air.lat))
# calculate regional averages
reg_ave = air.weighted(mask3D * wgt).mean(("lat", "lon"))
# calculate the average temperature (over 2013-2014)
avg_temp = reg_ave.sel(time=slice("2013", "2014")).mean("time")
# calculate the anomaly (w.r.t. 2013-2014)
reg_ave_anom = reg_ave - avg_temp
# select a single timestep (January 2013)
reg_ave_anom_ts = reg_ave_anom.sel(time="2013-01")
# remove the time dimension
reg_ave_anom_ts = reg_ave_anom_ts.squeeze(drop=True)
# convert to a pandas dataframe so it's in tabular form
df = reg_ave_anom_ts.air.to_dataframe()
# set the state codes as index
df = df.set_index("abbrevs")
# remove other columns
df = df.drop(columns="names")
您可以在regionmask 文檔( Working with geopandas )上找到如何使用自己的 shapefile 的信息。
免責聲明:我是 regionmask 的主要作者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.