如何根据日期索引将行添加到数据框的前面?

问题描述

我有一个看起来像这样的数据框。 Datedatetime的索引。每个日期都有1个条目。

              Count
Date             
2020-08-14     2
2020-08-15     2
2020-08-16     1

如何将行插入值为0的数据框的开头?插入的行数基于指定的日期。例如。如果日期为2020-08-09,则插入日期为2020-08-092020-08-13的行。输出看起来像这样:

             Count
Date          
2020-08-09     0
2020-08-10     0
2020-08-11     0
2020-08-12     0
2020-08-13     0 
2020-08-14     2
2020-08-15     2
2020-08-16     1

解决方法

您可以使用新的日期范围reindex

dr = pd.date_range('08-09-2020','08-16-2020',freq='1D')

df = df.reindex(dr).fillna(0)
,

您可以使用concat()

df = pd.concat([
    pd.DataFrame({"Date":pd.date_range(dt.datetime(2020,8,9),dt.datetime(2020,13)),"Count":0}).set_index("Date"),df
])
,

添加索引为code: 'ER_PARSE_ERROR',errno: 1064,sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Juri Boyka',`room` = '45',`team` = NULL,`city` = NULL,`hotel_na' at line 1",sqlState: '42000',index: 0,sql: "INSERT INTO rooms_split SET `id` = NULL,`workers` = 'John Snow','Juri Boyka',`hotel_name` = 'Test Hamburg',`address` = 'Hamburg 5,test Strase'" } 的行。 Timestamp('2020-08-09')Sort_index

asfreq