Skip to content
Advertisement

Creating a tumbling windows in python

Just wondering if there is a way to construct a tumbling window in python. So for example if I have list/ndarray , listA = [3,2,5,9,4,6,3,8,7,9]. Then how could I find the maximum of the first 3 items (3,2,5) -> 5, and then the next 3 items (9,4,6) -> 9 and so on… Sort of like breaking it up to sections and finding the max. So the final result would be list [5,9,8,9]

Advertisement

Answer

Approach #1: One-liner for windowed-max using np.maximum.reduceat

JavaScript

Becomes more compact with np.r_

JavaScript

Approach #2: Generic ufunc way

Here’s a function for generic ufuncs and that window length as a parameter –

JavaScript

Sample run –

JavaScript

On other ufuncs –

JavaScript

Benchmarking

Timings on NumPy solutions on array data with sample data scaled up by 10000x

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement