python - 使用 xarray 滚动分位数
问题描述
有没有办法在窗口xArray
上计算分位数?DataArray.rolling
列出的可用方法包括mean
or 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 times
x 2的案例研究中locations
,pandas
运行需要 0.015 秒,而运行construct
需要 1.25 秒。
解决方案
您可以使用滚动对象的construct
方法,它会生成一个DataArray
带有滚动维度的新对象。
signal.rolling(time=window, center=True).construct('tmp').quantile(.25, dim='tmp')
上面,我构造了一个具有附加tmp
维度的 DataArray 并沿该维度计算分位数。
推荐阅读
- python - 如何自定义页面类型模型的 IndexView - Wagtail Admin 中的列表视图
- python-3.x - 如何在 Python 中检查来自文件的用户输入?
- go - 成功连接 webscoket 后如何向特定 URI 发送消息?
- c# - HTTPWebRequest - GetResponse() - 在 SSIS C# 脚本中被远程主机强制关闭
- html - 通过 sqlite/flask 应用程序填充的 HTML 表显示原始代码而不是格式化代码
- algorithm - 最小生成树:prim and kruskal
- ios - SWIFT 如何从 GoogleMaps GMSAutocomplete 获取经纬度坐标?
- windows - 为什么 NRPT 规则不影响我的 Windows 10 机器上的 DNS 查询?
- android - 如何在颤动中从特定包中加载文件?
- php - 未定义变量:C:\xampp\htdocs\Auto\profile.php 中的 profile_data