0

Background

I want to perform a calculation on a Pandas Series. This calculation involves min and max. The calculation is used twice. In both cases it is the same calculation except for the min or max functions, which should be different.

I've created a function to perform this calculation:

def my_calc(my_series):
   return my_series.rolling(...).max()

The problem

I don't know how to pass max as a parameter of my_calc.

Attempts

  • This solution works only for basic operators.
  • Currently I use my_calc(my_series).max() and my_calc(my_series).min()
Community
  • 1
  • 1
Michael
  • 3,206
  • 5
  • 26
  • 44

4 Answers4

1

There's really no pretty way to do it.

def my_calc(my_series, func=max):
   if not func in {'min', 'max'}:
      raise ValueError('{} is not a valid method name!'.format(func))
   return getattr(my_series.rolling(...), func)()

foo = my_calc(some_series, 'min')
bar = my_calc(some_series, 'max')
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

Call my_calc with the name of the function as string, then use getattr:

def my_calc(my_series, func_name):
    try:
        return getattr(my_series.rolling(...), func_name)()
    except AttributeError:
        print('{} has no attribute {}'.format(type(my_series), func_name))

my_calc(my_series, 'min')
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
1

Try like this rolling_max

def my_calc(my_series):
  return my_series.rolling_max(...)
Ankanna
  • 737
  • 2
  • 8
  • 21
  • `FutureWarning: pd.rolling_min is deprecated for Series and will be removed in a future version, replace with Series.rolling(window=4320,center=False).min()` – Michael Jul 06 '16 at 12:58
1

You can use apply (or agg):

def my_calc(my_series, func):
   return my_series.rolling(...).apply(func)

And use like:

my_calc(ser, np.mean)
Out[321]: 
0    NaN
1    0.5
2    0.0
3    0.5
4    2.0
Name: a, dtype: float64
ayhan
  • 70,170
  • 20
  • 182
  • 203