python - 使用 xarray 滚动分位数

标签 python quantile python-xarray

有没有xArrayDataArray.rolling 上计算分位数的方法 window ?列出的可用方法包括 meanmedian ,但没有分位数/百分位数。我想知道即使没有直接的方法,是否可以以某种方式完成。

目前,我正在本地迁移 xArray数据到 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 times 的案例研究x 2 locations , pandas运行需要 0.015 秒,而 construct一个需要 1.25 秒。

最佳答案

您可以使用 construct method滚动对象,它生成一个新的具有滚动维度的 DataArray

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

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

关于python - 使用 xarray 滚动分位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607236/

相关文章:

python - xarray - 从另一个 DataArray 的时间标签中选择/索引 DataArray

python - netCDF4.Dataset 到 xarray 数据集的简单转换

python - 删除&q;并使用 json.loads 函数加载字符串

python - 在没有 "in"的情况下列出 Python 中的成员资格

statistics - 在 Julia 与 Python 中使用分位数时出现意外结果

python - 通过 Rpy 排序分位数平均值

python - 直接应用 numpy 梯度结果与使用 xarray.apply_ufunc 应用的结果之间的差异

python - 如何更改 scipy curve_fit/least_squares 步长?

python - 在 zeromq/python 中使用 pyobj 子函数时设置主题

r - 使用带有 ggplot 的两个向量的分位数-分位数图