Как построить график скользящих средних расходов по категориям?Python

Программы на Python
Anonymous
Как построить график скользящих средних расходов по категориям?

Сообщение Anonymous »

Goal
I have data that represent expenses, with date and category, and I want to plot the rolling average per category over time
Sources
I have tried using and combining the following without success
  • Python Pandas: Calculate moving average within group doesn't handle dates
  • Calculating monthly aggregate of expenses with pandas doesn't handle rolling average
Tries and MCVE
The best I've come with, using the second link is this

import pandas as pd from matplotlib import pyplot as plt from random import randrange, seed from datetime import datetime seed(321) nb = 24 df = pd.DataFrame({ "date": [datetime(2023, 1 + i // 2, 5) for i in range(nb)], "category": [item for _ in range(nb // 2) for item in ["food", "wear"]], "value": [randrange(10, 120) for _ in range(nb)], }) df.set_index("date", inplace=True) all_s = [] for x in set(df["category"]): s = df.loc[df['category'] == x, "value"] s = s.groupby(pd.Grouper(freq="ME")).sum() all_s.append(s.rename(x)) df = pd.concat(all_s, axis=1).fillna(0).asfreq("ME", fill_value=0) df.plot(style='.-', figsize=(15, 20), ylim=(0, 130)) plt.show() Rendering in


Изображение

Expectation
I expect to add something like a .rolling(window=3, min_periods=1) somewhere, to get kind of a flat line on the graph, to avoid peaks and just have an average over a given period


Источник: https://stackoverflow.com/questions/780 ... r-category

Вернуться в «Python»