15

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'
Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102
Stas Busygin
  • 305
  • 1
  • 2
  • 4
  • 2
    You may want to convert your data: http://stackoverflow.com/questions/13187778/pandas-dataframe-to-numpy-array-include-index – David Manheim Dec 24 '14 at 06:05

3 Answers3

22

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

nitin
  • 7,234
  • 11
  • 39
  • 53
2

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.

Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102
Tomasz Gandor
  • 8,235
  • 2
  • 60
  • 55
0

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))
Mir.Emad
  • 83
  • 8