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()
1
  • what is wrong with my_calc(my_series).max() & my_calc(my_series).min() if my_calc() returns rolling object? Commented Jul 6, 2016 at 12:55

4 Answers 4

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')
Sign up to request clarification or add additional context in comments.

Comments

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')

Comments

1

Try like this rolling_max

def my_calc(my_series):
  return my_series.rolling_max(...)

1 Comment

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()
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.