Skip to content
Advertisement

Filling empty months in pandas dataframe not working

I have a pandas DataFrame exclusively with dates:

JavaScript

Using groupby I get a count for the number of monthly occurrences as seen below:

JavaScript

(date is only used for plotting reasons). My issue is, come 09-2021 I have zero monthly counts and I want to obtain my gh dataframe such that the missing rows look something like:

JavaScript

All the way through 06-2022.

I encounter errors when I try using gh.reindex(pd.period_range(gh.index[0], gh.index[-1], freq='M')) from this solution, as the monthly indexes repeat. I also think because I’m only working with dates as my data and not actual variables, this is messing things up, but i am trying to plot each month from 01/2019 – 06/2022 including the 0 counts for months in late 2021 and early 2022. How do I make this work?

I know there are a lot of threads similar to this, but they all use actual data counts, and not just date counts.

Edit: Here is the output from df.info():

JavaScript

Advertisement

Answer

Create a MultiIndex then reindex after groupby_agg:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement