简体   繁体   中英

How to get the rolling(window = 3).max() on a numpy.ndarray?

I have a numpy.ndarray as follow. It's the output from talib.RSI. It's the type of numpy.ndarray. I want to get the list of rolling(windows=3).max() and the rolling(window=3).min

How to do that?

[         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]

If you can afford adding a new dependency, I would rather do that with 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())

Note that converting your NumPy array to a Pandas series does not create a copy of the array, as Pandas uses NumPy arrays internally for its series.

You can use 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM