在pythonxarray中减去每个网格的月平均值的最佳方法
玩具数据集来自: 我知道我可以在在pythonxarray中减去每个网格的月平均值的最佳方法,python,python-xarray,Python,Python Xarray,玩具数据集来自: 我知道我可以在xarray.DataSet()中找到如何从变量中减去月平均值的方法,如下所示: climatology = ds.groupby("time.month").mean("time") anomalies = ds.groupby("time.month") - climatology anomalies.mean("location").to_dataframe()[["t
xarray.DataSet()
中找到如何从变量中减去月平均值的方法,如下所示:
climatology = ds.groupby("time.month").mean("time")
anomalies = ds.groupby("time.month") - climatology
anomalies.mean("location").to_dataframe()[["tmin", "tmax"]].plot()
那么,我能为每个位置做减法吗
我尝试对位置月组执行此操作,但xarray.DataSet.groupby()
不允许传递多个组。然后,我尝试使用xarray.DataSet.stack()
创建位置月,但它只允许传递维度;我可以使用time.month
提取月份值,但它们被恢复为一个新变量,而不是维度。我可以对所有位置使用或xarray.DataSet.apply()
,但速度太慢(我有大约65000个位置)
预期结果或过程类似于:
for each location:
climatology = ds.groupby("time.month").mean("time")
anomalies = ds.groupby("time.month") - climatology
仅在xarray
中使用解决方案是最好的,但是如果使用pd.DataFrame()
或其他解决方案是可能的并且非常快,那么这些解决方案也是受欢迎的
编辑
下面是我当前使用'pd.DataFrame()'的解决方案
for each location:
climatology = ds.groupby("time.month").mean("time")
anomalies = ds.groupby("time.month") - climatology
# convert to pd.dataframe
df = ds.to_dataframe()
# get mean monthly values
months = df.index.get_level_values('time').month
df_meanMonths = df.groupby([pd.Grouper(level='location'), months]).mean()
# rename and reindex
df_meanMonths.rename(columns={'tmin': 'tminMM', 'tmax': 'tmaxMM'}, inplace=True)
df_meanMonths.index.set_names('month', level='time', inplace=True)
# merge
df['month'] = df.index.get_level_values('time').month
vars_join = ['tminMM', 'tmaxMM']
join_right = df_meanMonths[vars_join]
# results
df.reset_index().set_index(['location', 'month']).merge(join_right, how='left', left_index=True, right_on=['location', 'month'])