【问题标题】:How to get the rolling(window = 3).max() on a numpy.ndarray?如何在 numpy.ndarray 上获取 rolling(window = 3).max()?
【发布时间】:2017-12-11 18:41:16
【问题描述】:

我有一个 numpy.ndarray 如下。这是 talib.RSI 的输出。它是 numpy.ndarray 的类型。我想得到 rolling(windows=3).max() 和 rolling(window=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]

【问题讨论】:

  • stackoverflow.com/questions/6811183/… 的可能重复项(只需将 std 更改为 max
  • 您希望如何处理NaNs?就像一个有一个非 NaN 的窗口一样,您希望它的输出是 NaN 还是 non-NaN
  • 为什么不使用 Pandas?
  • 我必须摆脱许多 nan。我想要非 NaN。
  • 为什么不使用 Pandas?因为 talib.RSI 的输出是 numpy.ndarray 的类型。

标签: python numpy


【解决方案1】:

如果您负担得起添加新依赖项,我宁愿使用 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 数组。

【讨论】:

    【解决方案2】:

    你可以使用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]
    

    【讨论】:

    • 您好,我尝试了您的代码,但出现如下错误:SecurityViolation: 0002 Security Violation(s): Insecure attribute access "numpy.lib.stride_tricks"。
    • 然后试试pd.Series(arr).rolling(window=3).sum().max()
    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 2014-08-04
    • 1970-01-01
    • 2022-07-21
    • 2021-04-27
    • 2019-07-08
    相关资源
    最近更新 更多