有没有xArray
在 DataArray.rolling
上计算分位数的方法 window ?列出的可用方法包括 mean
或 median
,但没有分位数/百分位数。我想知道即使没有直接的方法,是否可以以某种方式完成。
目前,我正在本地迁移 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/