Language/Python

[Python] Sliding Window

Linuxias 2023. 8. 24. 11:57
반응형
def sliding_window(series, window_size, step = 1):
    """series is a column of a dataframe"""
    for start_row in range(0, len(series) - window_size + 1, step):
        yield series[start_row:start_row + window_size]

tmp = np.arange(100)
list(sliding_window(tmp, 10, 5))

위의 코드를 실행하면 0부터 99까지의 데이터를 10개씩 5개씩 이동하면서 데이터를 만들어낸다. 결과는 아래와 같다.

[array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
 array([ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14]),
 array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),
 array([15, 16, 17, 18, 19, 20, 21, 22, 23, 24]),
 array([20, 21, 22, 23, 24, 25, 26, 27, 28, 29]),
 array([25, 26, 27, 28, 29, 30, 31, 32, 33, 34]),
 array([30, 31, 32, 33, 34, 35, 36, 37, 38, 39]),
 array([35, 36, 37, 38, 39, 40, 41, 42, 43, 44]),
 array([40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
 array([45, 46, 47, 48, 49, 50, 51, 52, 53, 54]),
 array([50, 51, 52, 53, 54, 55, 56, 57, 58, 59]),
 array([55, 56, 57, 58, 59, 60, 61, 62, 63, 64]),
 array([60, 61, 62, 63, 64, 65, 66, 67, 68, 69]),
 array([65, 66, 67, 68, 69, 70, 71, 72, 73, 74]),
 array([70, 71, 72, 73, 74, 75, 76, 77, 78, 79]),
 array([75, 76, 77, 78, 79, 80, 81, 82, 83, 84]),
 array([80, 81, 82, 83, 84, 85, 86, 87, 88, 89]),
 array([85, 86, 87, 88, 89, 90, 91, 92, 93, 94]),
 array([90, 91, 92, 93, 94, 95, 96, 97, 98, 99])]
반응형