我有一個包含兩列的 Pandas DataFrame:id和processing_date.
后者是處理專案 (id) 的日期。
import pandas as pd
# df
id processed_date
324 2016-07-08
A550 2016-07-09
79 2016-08-10
C295 2016-08-10
413 2016-08-11
...
111 2021-11-08
709 2021-11-08
我想繪制一個顯示每個月處理的專案數量的圖表和一個“幾個月內”的累積圖表。由于我有 5 年零 4 個月的資料,因此我必須有 64 個條目和 64 個資料點才能繪制為條形圖或折線圖。
這是我從這里得到的,但它沒有按預期作業:
df['date'] = pd.to_datetime(df['processed_date']) # needed by the nature of the data
df.set_index('date')
df = df.groupby('date')['id'].count() # <- this will stack items per day
df = df.groupby(df.index.month)['id'].count() # <- this will stack items per 12 months, but I have 5 years and 4 months of data, hence 64 different months, not 12.
我怎么能做到這一點?
理想輸出:
# df
nb_items_processed cum_sum year_month
2 2 2016-07
3 5 2016-08
...
2 xxx 2021-11
uj5u.com熱心網友回復:
從groupby().size()每月計數開始,然后在沒有 groupby 的情況下進行 cumsum:
out = df.groupby(pd.Grouper(key='processed_date', freq='M')).size().reset_index(name='nb_items_processed')
out['cum_sum'] = out['nb_items_processed'].cumsum()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/353668.html
