Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rolling apply function must be real number, not Nonetype

Tags:

python

pandas

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 !

like image 277
whtitefall Avatar asked Mar 04 '20 00:03

whtitefall


People also ask

What is rollapply() function?

A generic function for applying a function to rolling margins of an array. rollapply (data, …) # S3 method for ts rollapply (data, …)

How do I apply the Rolling function to a partial window?

The rolling function can also be applied to partial windows by setting partial = TRUE For example, if width = 3, align = "right" then for the first point just that point is passed to FUN since the two points to its left are out of range. For the same example, if partial = FALSE then FUN is not invoked at all for the first two points.

Can the apply function return a single value in pandas?

Thanks ! Show activity on this post. 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. Thanks for contributing an answer to Stack Overflow!


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)
like image 105
A.Vignon Avatar answered Oct 23 '22 03:10

A.Vignon