首页 > 解决方案 > 使用 xarray 滚动分位数

问题描述

有没有办法在窗口xArray上计算分位数?DataArray.rolling列出的可用方法包括meanor median,但没有分位数/百分位数。我想知道这是否可以以某种方式完成,即使没有直接的方法。

目前,我正在本地将xArray数据迁移到 a pandas.DataFrame,并在其中应用rolling().quantile()序列。之后,我采用新的价值观并从中DataFrame建立一个。xArray.DataArray可重现的代码:

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

times = np.arange(0, 30)
locs = ['A', 'B', 'C', 'D'] 

signal = xr.DataArray(np.random.rand(len(times), len(locs)), 
                      coords=[times, locs], dims=['time', 'locations'])
window = 5

df = pd.DataFrame(data=signal.data)
roll = df.rolling(window=window, center=True, axis=0).quantile(.25).dropna()
window_array = xr.DataArray(roll.values, 
            coords=[np.arange(0, signal.time.shape[0] - window + 1), signal.locations], 
            dims=['time', 'locations'])

欢迎任何尽可能坚持的线索xArray

让我们考虑同样的问题,只是规模更小(10 个时间实例,2 个位置)。

这是第一种方法的输入(通过pandas):

<xarray.DataArray (time: 8, locations: 2)>
array([[0.404362, 0.076203],
       [0.353639, 0.076203],
       [0.387167, 0.102917],
       [0.525404, 0.298231],
       [0.755646, 0.298231],
       [0.460749, 0.414935],
       [0.104887, 0.498813],
       [0.104887, 0.420935]])
Coordinates:
* time       (time) int32 0 1 2 3 4 5 6 7
* locations  (locations) <U1 'A' 'B'

请注意,由于调用dropna()滚动对象,“时间”维度较小。新的维度大小基本上是len(times) - window + 1. 现在,建议方法的输出(通过construct):

<xarray.DataArray (time: 10, locations: 2)>
array([[0.438426, 0.127881],
       [0.404362, 0.076203],
       [0.353639, 0.076203],
       [0.387167, 0.102917],
       [0.525404, 0.298231],
       [0.755646, 0.298231],
       [0.460749, 0.414935],
       [0.104887, 0.498813],
       [0.104887, 0.420935],
       [0.112651, 0.60338 ]])
Coordinates:
* time       (time) int32 0 1 2 3 4 5 6 7 8 9
* locations  (locations) <U1 'A' 'B'

看起来尺寸仍然(time, locations)是 ,前者的大小等于 10,而不是 8。在此处的示例中,因为center=True,如果删除第二个数组中的第一行和最后一行,两个结果是相同的。不应该DataArray有一个新的维度tmp吗?

此外,这种方法(bottleneck已安装)比最初通过pandas. 例如,在 1000 timesx 2的案例研究中locationspandas运行需要 0.015 秒,而运行construct需要 1.25 秒。

标签: pythonquantilepython-xarray

解决方案


您可以使用滚动对象的construct方法,它会生成一个DataArray带有滚动维度的新对象。

signal.rolling(time=window, center=True).construct('tmp').quantile(.25, dim='tmp')

上面,我构造了一个具有附加tmp维度的 DataArray 并沿该维度计算分位数。


推荐阅读