Скользящие средние значения Pandas для дат после группировки по ⇐ Python
Скользящие средние значения Pandas для дат после группировки по
df = pd.DataFrame( {"date": [pd.Timestamp("2022-01-01"), pd.Timestamp("2022-01-01"), pd.Timestamp("2022-01-01"), pd.Timestamp("2022-01-03"), pd.Timestamp("2022-01-03"), pd.Timestamp("2022-01-03"), pd.Timestamp("2022-01-05")], "numbers": [1,2,4,4,11,7,5], "grouper": [1, 0, 1, 0,1, 0, 0] } ) If I have the following df and I would like to get the rolling mean for the values of numbers that are before each rows date column, how would I do that? eg. the rolling averages for the past 3 days for grouped by ["grouper", "date"]
I know I can do something like this, but not even close to a solution -
I am looking to build on this solution
df["av"] = df.shift(1).rolling(window=3).mean() but this does not shift dynamically so it includes today.
My expected output for the new av column for a 3 day window grouped by the two columns of the sample df would be
date numbers grouper av 0 2022-01-01 1 1 NaN 1 2022-01-01 2 0 NaN 2 2022-01-01 4 1 NaN 3 2022-01-03 4 0 2.0 4 2022-01-03 11 1 2.5 5 2022-01-03 7 0 2.0 6 2022-01-05 5 0 5.5
Источник: https://stackoverflow.com/questions/747 ... r-group-by
df = pd.DataFrame( {"date": [pd.Timestamp("2022-01-01"), pd.Timestamp("2022-01-01"), pd.Timestamp("2022-01-01"), pd.Timestamp("2022-01-03"), pd.Timestamp("2022-01-03"), pd.Timestamp("2022-01-03"), pd.Timestamp("2022-01-05")], "numbers": [1,2,4,4,11,7,5], "grouper": [1, 0, 1, 0,1, 0, 0] } ) If I have the following df and I would like to get the rolling mean for the values of numbers that are before each rows date column, how would I do that? eg. the rolling averages for the past 3 days for grouped by ["grouper", "date"]
I know I can do something like this, but not even close to a solution -
I am looking to build on this solution
df["av"] = df.shift(1).rolling(window=3).mean() but this does not shift dynamically so it includes today.
My expected output for the new av column for a 3 day window grouped by the two columns of the sample df would be
date numbers grouper av 0 2022-01-01 1 1 NaN 1 2022-01-01 2 0 NaN 2 2022-01-01 4 1 NaN 3 2022-01-03 4 0 2.0 4 2022-01-03 11 1 2.5 5 2022-01-03 7 0 2.0 6 2022-01-05 5 0 5.5
Источник: https://stackoverflow.com/questions/747 ... r-group-by
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение