从pandas.Series中选择本地最小值和最大值

时间:2014-12-24 05:58:59

标签: python pandas

scipy.signal.argrelextrema函数适用于ndarray,但当我尝试在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'

3 个答案:

答案 0 :(得分:14)

您可能希望像这样使用它,

argrelextrema(s.values, np.greater)

您目前正在使用完整的pandas系列,而argrelextrema需要一个nd数组。 s.values为您提供了nd.array

答案 1 :(得分:0)

尽管s.values仍然可以正常使用(熊猫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的意思是“不要强行复制”,但仍然可能发生。

答案 2 :(得分:0)

最新回复 正如您的代码所示,已被熊猫读取的数组应该转向numpy array。因此,只需尝试通过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))