简体   繁体   中英

Selecting local minima and maxima from pandas.Series

There is a scipy.signal.argrelextrema function that works with ndarray , but when I try to use it on pandas.Series , it returns an error. What's the right way to use it with pandas?

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'

You probably want to use it like so,

argrelextrema(s.values, np.greater)

You are currently using the complete pandas Series while argrelextrema expects an nd array. s.values provides you with the nd.array

Even though s.values still works fine (Pandas 0.25), the recommended way is now:

argrelextrema(s.to_numpy(), np.greater)
# equivalent to:
argrelextrema(s.to_numpy(copy=False), np.greater)

While there is also an s.array property, using it here will fail with: TypeError: take() got an unexpected keyword argument 'axis' .

Note: copy=False means "don't force a copy", but it can still happen.

Late reply As your code showed up, your array which has been read by pandas should be turning to numpy array. So just try to change the data frame to numpy array by np.array

g = np.array(s) # g is new variable notation
argrelextrema(g, np.greater)

or in a different shape

g = np.array(s) # g is new variable notation
argrelextrema(g, lambda a,b: (a>b) | (a<b))

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