微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有一个看起来像这样的数据框。 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。