如何在numpy.ndarray上获得滚动(window = 3).max()?

时间:2017-07-07 12:51:11

标签: python numpy

我有一个numpy.ndarray如下。它是talib.RSI的输出。这是numpy.ndarray的类型。我想得到滚动列表(windows = 3).max()和滚动(窗口= 3).min

怎么做?

[         nan          nan          nan          nan          nan
          nan          nan          nan          nan          nan
          nan          nan          nan          nan  56.50118203
  60.05461743  56.99068148  55.70899949  59.2299361   64.19044898
  60.62186599  53.96346826  44.06538636  52.04519976  51.32884016
  58.65240379  60.44789401  58.94743634  59.75308787  53.56534397
  54.22091468  47.22502341  51.5425848   50.0923126   49.80608264
  45.69087847  50.07778871  54.21701441  58.79268406  63.59307774
  66.08195696  65.49255218  65.11035657  68.47403716  70.70530564
  73.21955929  76.57474822  65.89852612  66.51497688  72.42658468
  73.80944844  69.56561001]

2 个答案:

答案 0 :(得分:2)

如果您能负担得起添加新依赖项,我宁愿使用Pandas

import numpy
import pandas


x = numpy.array([0, 1, 2, 3, 4])
s = pandas.Series(x)

print(s.rolling(3).min())
print(s.rolling(3).max())
print(s.rolling(3).mean())
print(s.rolling(3).std())

请注意,将NumPy数组转换为Pandas系列不会创建数组副本,因为Pandas会在内部为其系列使用NumPy数组。

答案 1 :(得分:1)

您可以使用np.lib.stride_tricks.as_strided

# a smaller example
import numpy.random as npr
npr.seed(123)
arr = npr.randn(10)
arr[:4] = np.nan    

windows = np.lib.stride_tricks.as_strided(arr, shape=(8, 3), strides=(8, 8))

print(windows.max(axis=1))
print(windows.sum(axis=1))
[        nan         nan         nan         nan  1.65143654  1.65143654
  1.26593626  1.26593626]
[        nan         nan         nan         nan -1.35384296 -1.20415534
 -1.58965561 -0.02971677]