Add missing dates to pandas dataframe

前端 未结 5 2184
春和景丽
春和景丽 2020-11-22 09:47

My data can have multiple events on a given date or NO events on a date. I take these events, get a count by date and plot them. However, when I plot them, my two series do

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 10:19

    Here's a nice method to fill in missing dates into a dataframe, with your choice of fill_value, days_back to fill in, and sort order (date_order) by which to sort the dataframe:

    def fill_in_missing_dates(df, date_col_name = 'date',date_order = 'asc', fill_value = 0, days_back = 30):
    
        df.set_index(date_col_name,drop=True,inplace=True)
        df.index = pd.DatetimeIndex(df.index)
        d = datetime.now().date()
        d2 = d - timedelta(days = days_back)
        idx = pd.date_range(d2, d, freq = "D")
        df = df.reindex(idx,fill_value=fill_value)
        df[date_col_name] = pd.DatetimeIndex(df.index)
    
        return df
    

提交回复
热议问题