Pandas 二十四:怎么处理日期索引的缺失?
问题:按日期统计的数据,缺失了某天,导致数据不全该怎么补充日期?
可以用两种方法实现:
1、DataFrame.reindex,调整dataframe的索引以适应新的索引
2、DataFrame.resample,可以对时间序列重采样,支持补充缺失值
问题:如果缺失了索引该怎么填充?
1
import pandas as pd
%matplotlib inline
2
df = pd.DataFrame({
"pdate": ["2019-12-01", "2019-12-02", "2019-12-04", "2019-12-05"],
"pv": [100, 200, 400, 500],
"uv": [10, 20, 40, 50],
})
df
2
pdate pv uv
0 2019-12-01 100 10
1 2019-12-02 200 20
2 2019-12-04 400 40
3 2019-12-05 500 50
3
df.set_index("pdate").plot()
3

问题,这里缺失了2019-12-03的数据,导致数据不全该怎么补充?
方法1:使用pandas.reindex方法
1、将df的索引变成日期索引
4
df_date = df.

本文介绍了如何使用Pandas的reindex和resample方法来处理日期索引缺失的问题。通过设置日期索引,然后使用reindex填充缺失的日期并设置默认值,或者利用resample进行时间序列重采样,填补空缺值。这两种方法对于按日期统计的数据不完整情况提供了有效的解决方案。
最低0.47元/天 解锁文章
1120

被折叠的 条评论
为什么被折叠?



