Search code examples
pythonpandasdate-range

how to add values to specific date in pandas?


So I have a dataset with a specific date along with every data. I want to fill these values according to their specific date in Excel which contains the date range of the whole year. It's like the date starts from 01-01-2020 00:00:00 and end at 31-12-2020 23:45:00 with the frequency of 15 mins. So there will be a total of 35040 date-time values in Excel. my data is like:

load  date
 12    01-02-2020 06:30:00
 21    29-04-2020 03:45:00
 23    02-07-2020 12:15:00
 54    07-08-2020 16:00:00
 23    22-09-2020 16:30:00

As you can see these values are not continuous but they have specific dates with them, so I these date values as the index and put it at that particular date in the Excel which has the date column, and also put zero in the missing values. Can someone please help?


Solution

  • Use DataFrame.reindex with date_range - so added 0 values for all not exist datetimes:

    rng = pd.date_range('2020-01-01','2020-12-31 23:45:00', freq='15Min') 
    
    df['date'] = pd.to_datetime(df['date'])
    df = df.set_index('date').reindex(rng, fill_value=0)
    
    print (df)
                         load
    2020-01-01 00:00:00     0
    2020-01-01 00:15:00     0
    2020-01-01 00:30:00     0
    2020-01-01 00:45:00     0
    2020-01-01 01:00:00     0
                      ...
    2020-12-31 22:45:00     0
    2020-12-31 23:00:00     0
    2020-12-31 23:15:00     0
    2020-12-31 23:30:00     0
    2020-12-31 23:45:00     0
    
    [35136 rows x 1 columns]