Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在pythonxarray中减去每个网格的月平均值的最佳方法_Python_Python Xarray - Fatal编程技术网

在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'])