【问题标题】:python-xarray: rolling mean examplepython-xarray:滚动平均值示例
【发布时间】:2018-02-10 02:10:21
【问题描述】:

我有一个文件是一年的月度数据(12 分)。数据从 12 月开始,到 11 月结束。我希望创建一个 3 个月的运行平均文件,即 DJF、JFM、...、SON(10 分)

我注意到有一个DataArray.rolling 函数返回一个滚动窗口选项,我认为这对此很有用。但是,我还没有找到任何使用滚动功能的示例。我承认我不熟悉bottleneckpandas.rolling_mean 或更新的pandas.rolling,所以我的入门级别相当低。

这里有一些代码要测试:

import numpy as np
import pandas as pd
import xarray as xr

lat = np.linspace(-90, 90, num=181); lon = np.linspace(0, 359, num=360)
# Define monthly average time as day in middle of month
time = pd.date_range('15/12/1999', periods=12, freq=pd.DateOffset(months=1))
# Create data as 0:11 at each grid point
a = np.linspace(0,11,num=12)
# expand to 2D
a2d = np.repeat(tmp[:, np.newaxis], len(lat), axis=1)
# expand to 3D
a3d = np.repeat(a2d[:, :, np.newaxis], len(lon), axis=2)
# I'm sure there was a cleaner way to do that...

da = xr.DataArray(a3d, coords=[time, lat, lon], dims=['time','lat','lon'])  

# Having a stab at the 3-month rolling mean
da.rolling(dim='time',window=3).mean()
# Error output:
Traceback (most recent call last):
File "<ipython-input-132-9d64cc09c263>", line 1, in <module>
da.rolling(dim='time',window=3).mean()
File "/Users/Ray/anaconda/lib/python3.6/site-packages/xarray/core/common.py", line 478, in rolling
center=center, **windows)
File "/Users/Ray/anaconda/lib/python3.6/site-packages/xarray/core/rolling.py", line 126, in __init__
center=center, **windows)
File "/Users/Ray/anaconda/lib/python3.6/site-packages/xarray/core/rolling.py", line 62, in __init__
raise ValueError('exactly one dim/window should be provided')

ValueError: 应该只提供一个暗淡/窗口

【问题讨论】:

    标签: pandas python-xarray


    【解决方案1】:

    你很亲密。 rolling method 采用映射为 dim/window_size 的键/值对。这应该适合你。

    da.rolling(time=3).mean()
    

    【讨论】:

    • 谢谢。我想到放弃 nans 的最简单方法就是 da.rolling(time=winlen).mean()[winlen-1::,:,:] 不确定是否有更好的方法。请注意,如果我做一点 PR 以将此示例添加到 github.com/pydata/xarray/blob/master/xarray/core/rolling.py 的文档中,是否有滚动对象可用的功能列表,例如平均值、总和、中位数等?
    • 因此,您可以做两件事来帮助 nans:1) 您可以将 min_periods 设置为整数(例如 da.rolling(min_periods=0, time=3).mean()),或者 2) 您可以使用dropna(例如 da.rolling(time=3).mean().dropna('time)`)。我们始终欢迎帮助改进 xarray 文档的人们。
    猜你喜欢
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2021-12-18
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多