Rolling apply function must be real number, not Nonetype

Viewed 2238

I'm trying to use rolling and apply function to print window

but I got the error says

File "pandas/_libs/window.pyx", line 1649, in pandas._libs.window.roll_generic
TypeError: must be real number, not NoneType

My code is following

def print_window(window):
  print(window)
  print('==================')


def example():

  df = pd.read_csv('window_example.csv')

  df.rolling(5).apply(print_window)

My data is like

number    sum   mean 
  1        1     1
  2        3     1.5
  3        6     2
  4       10     2.5
  5       15     3
  6       20     4

How should I slove this error? I didn't find similar questions on this error

Thanks !

1 Answers

This behavior appeared in pandas=1.0.0. The function of the apply is now expected to return a single value to affect the corresponding column with.

https://pandas.pydata.org/pandas-docs/version/1.0.0/reference/api/pandas.core.window.rolling.Rolling.apply.html#pandas.core.window.rolling.Rolling.apply

A workaround for your code would be :

def print_window(window):
  print(window)
  print('==================')
  return 0


def example():

  df = pd.read_csv('window_example.csv')

  df.rolling(5).apply(print_window)
Related