[英]How to find all local maxima and minima in a Python Pandas series without knowing the frequency of the window
[英]Selecting local minima and maxima from pandas.Series
有一個適用於ndarray
的scipy.signal.argrelextrema
函數,但是當我嘗試在pandas.Series
上使用它時,它返回一個錯誤。 將它與熊貓一起使用的正確方法是什么?
import numpy as np
import pandas as pd
from scipy.signal import argrelextrema
s = pd.Series(randn(10), range(10))
s
argrelextrema(s, np.greater)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-f3812e58bbe4> in <module>()
4 s = pd.Series(randn(10), range(10))
5 s
----> 6 argrelextrema(s, np.greater)
/usr/lib/python2.7/dist-packages/scipy/signal/_peak_finding.pyc in argrelextrema(data, comparator, axis, order, mode)
222 """
223 results = _boolrelextrema(data, comparator,
--> 224 axis, order, mode)
225 return np.where(results)
226
/usr/lib/python2.7/dist-packages/scipy/signal/_peak_finding.pyc in _boolrelextrema(data, comparator, axis, order, mode)
60
61 results = np.ones(data.shape, dtype=bool)
---> 62 main = data.take(locs, axis=axis, mode=mode)
63 for shift in xrange(1, order + 1):
64 plus = data.take(locs + shift, axis=axis, mode=mode)
TypeError: take() got an unexpected keyword argument 'mode'
你可能想像這樣使用它,
argrelextrema(s.values, np.greater)
您當前正在使用完整的熊貓系列,而 argrelextrema 需要一個 nd 數組。 s.values 為您提供 nd.array
即使s.values
仍然可以正常工作(Pandas 0.25),現在推薦的方法是:
argrelextrema(s.to_numpy(), np.greater)
# equivalent to:
argrelextrema(s.to_numpy(copy=False), np.greater)
雖然還有一個s.array
屬性,在這里使用它會失敗: TypeError: take() got an unexpected keyword argument 'axis'
。
注意: copy=False
表示“不強制復制”,但它仍然可能發生。
遲到的回復當你的代碼顯示出來時,你的被熊貓讀取的數組應該轉向 numpy 數組。 所以只需嘗試通過np.array
將數據框更改為 numpy 數組
g = np.array(s) # g is new variable notation
argrelextrema(g, np.greater)
或以不同的形狀
g = np.array(s) # g is new variable notation
argrelextrema(g, lambda a,b: (a>b) | (a<b))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.