[Python] Taking first and last value in a rolling window

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    Initial problem statement


    Using pandas, I would like to apply function available for resample() but not for rolling().

    This works:

    df1 = df.resample(to_freq,
    closed='left',
    kind='period',
    ).agg(OrderedDict([('Open', 'first'),
    ('Close', 'last'),
    ]))


    This doesn't:

    df2 = df.rolling(my_indexer).agg(
    OrderedDict([('Open', 'first'),
    ('Close', 'last') ]))
    >>> AttributeError: 'first' is not a valid function for 'Rolling' object

    df3 = df.rolling(my_indexer).agg(
    OrderedDict([
    ('Close', 'last') ]))
    >>> AttributeError: 'last' is not a valid function for 'Rolling' object


    What would be your advice to keep first and last value of a rolling windows to be put into two different columns?

    EDIT 1 - with usable input data


    import pandas as pd
    from random import seed
    from random import randint
    from collections import OrderedDict

    # DataFrame
    ts_1h = pd.date_range(start='2020-01-01 00:00+00:00', end='2020-01-02 00:00+00:00', freq='1h')
    seed(1)
    values = [randint(0,10) for ts in ts_1h]
    df = pd.DataFrame({'Values' : values}, index=ts_1h)

    # First & last work with resample
    resampled_first = df.resample('3H',
    closed='left',
    kind='period',
    ).agg(OrderedDict([('Values', 'first')]))
    resampled_last = df.resample('3H',
    closed='left',
    kind='period',
    ).agg(OrderedDict([('Values', 'last')]))

    # They don't with rolling
    rolling_first = df.rolling(3).agg(OrderedDict([('Values', 'first')]))
    rolling_first = df.rolling(3).agg(OrderedDict([('Values', 'last')]))


    Thanks for your help! Bests,

    Continue reading...

Compartilhe esta Página