Skip to content Skip to sidebar Skip to footer

Group By And Fill Missing Datetime Values

What I'm just trying is to group a Pandas Dataframe by contract and date, and fill missing datetime values. My input is this: contract datetime value1

Solution 1:

You can use DataFrame.reindex per groups with DataFrame.groupby and lambda function:

df['datetime'] = pd.to_datetime(df['datetime'])

f= lambda x: x.reindex(pd.date_range(x.index.min().floor('d'),
                                      .index.max().floor('d')+pd.Timedelta(23, 'H'),freq='H'))
df1 = (df.set_index('datetime')
         .groupby('contract')
         .apply(f)
         .drop('contract', axis=1)
         .reset_index())
print (df1)

Post a Comment for "Group By And Fill Missing Datetime Values"