如何解决在 Python xarray 中减去每个网格的平均月值的最佳方法
来自 here 的玩具数据集:
class Season(models.Model):
season = models.CharField(max_length=10)
buyer = models.ForeignKey(Buyer,on_delete=models.CASCADE)
fruit = models.ForeignKey(Fruit,on_delete=models.CASCADE)
我知道 here 我可以找到如何从 import numpy as np
import pandas as pd
import seaborn as sns
import xarray as xr
np.random.seed(123)
xr.set_options(display_style="html")
times = pd.date_range("2000-01-01","2001-12-31",name="time")
annual_cycle = np.sin(2 * np.pi * (times.dayofyear.values / 365.25 - 0.28))
base = 10 + 15 * annual_cycle.reshape(-1,1)
tmin_values = base + 3 * np.random.randn(annual_cycle.size,3)
tmax_values = base + 10 + 3 * np.random.randn(annual_cycle.size,3)
ds = xr.Dataset(
{
"tmin": (("time","location"),tmin_values),"tmax": (("time",tmax_values),},{"time": times,"location": ["IA","IN","IL"]},)
中的变量中减去平均每月值,如下所示:
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
或 for
,但速度太慢(我有大约 65000 个位置)。
预期的结果或过程类似于:
xarray.DataSet.apply()
仅在 for each location:
climatology = ds.groupby("time.month").mean("time")
anomalies = ds.groupby("time.month") - climatology
范围内的解决方案是最好的,但如果使用 xarray
或其他解决方案可行且速度相当快,那么也欢迎使用这些解决方案。
编辑
这是我目前使用 `pd.DataFrame()' 的解决方案
pd.DataFrame()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。