Skip to content Skip to sidebar Skip to footer

How Do I Create A Period Range Of Months And Fill It With Zeroes?

Suppose I have a dataframe containing certain events that happen in each month. The data only have months and years of the events and how many of that events happen every month. df

Solution 1:

Use period_range, then convert periods column to PeriodIndex and use DataFrame.reindex:

df['month'] = pd.to_datetime(df['month']).dt.to_period('M')
idx = pd.period_range(df['month'].min(), df['month'].max(), freq='M')
df = df.set_index('month').reindex(idx, fill_value=0)
print (df)
         counts
2018-01      10
2018-02       5
2018-03       0
2018-04       6
2018-05       1
2018-06       2
2018-07       5
2018-08       0
2018-09       0
2018-10       7
2018-11       8
2018-12       0
2019-01       9
2019-02       1
2019-03      10
2019-04       0
2019-05      12
2019-06       0
2019-07       8
2019-08       0
2019-09       0
2019-10       0
2019-11      10
2019-12       4

Post a Comment for "How Do I Create A Period Range Of Months And Fill It With Zeroes?"