[Python] Applying AverageIfs function for each row in a dataframe in Phython

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

  1. Stack

    Stack Membro Participativo

    I have a time series with two columns: "Date" and "Values". Based on the "Date" column, I have to calculate the 3y before dates which is OK. The name of this column is "Date3yBefore".

    Then, as a final step, I would like to create a new column by applying an averageifs function for each row of the dataframe where the average range is the "Values" column and the criteria are the "Date3yBefore" and the "Date" columns (so I would like to get the averages between these dates).

    The following code does not result in error however, the average values are the same for each row:

    df['AVG3y']= df[df['Date'].between(df['Date3yBefore'],df['Date'])]['Values'].mean()

    The current result looks like this:

    [​IMG]

    Could you please help me how I can modify the code to get the desired result? Thank you very much.

    Continue reading...

Compartilhe esta Página