0

I have a dataframe with a Period column.

         P   X
0  2021-02   4
1  2021-04  99
2  2021-07  41
3  2021-08  43

I want to fill the gaps (the other not shown months between Feb. and Aug. 2021) with X=0 like this.

         P   X
0  2021-02   4
1  2021-03   0
2  2021-04  99
3  2021-05   0
4  2021-06   0
5  2021-07  41
6  2021-08  43

Of course I could iterate somehow. But I assume there is a much more elegant pandas solution.

This is the MWE to produce the data.

#!/usr/bin/env python3
import pandas as pd

df = pd.DataFrame({
    'P': [pd.Period(f'2021-0{m}', freq='M') for m in [2, 4, 7, 8]],
    'X': [4, 99, 41, 43],
})

print(df)
buhtz
  • 10,774
  • 18
  • 76
  • 149
  • 1
    I think [this](https://stackoverflow.com/questions/17343726/pandas-add-data-for-missing-months) answer will help? – sophocles Sep 12 '22 at 15:10
  • `df_i = df.set_index(df['P']); df_i.reindex(pd.period_range(df.P.min(),df.P.max()))['X'].fillna(0)` in case you needed a solution – sayan dasgupta Sep 12 '22 at 15:18

0 Answers0