Pandas怎么处理日期索引的缺失?
问题:按日期统计的数据,缺失了某天,导致数据不全该怎么补充日期?
公众号:蚂蚁学Python
可以用两种方法实现:
1、DataFrame.reindex,调整dataframe的索引以适应新的索引
2、DataFrame.resample,可以对时间序列重采样,支持补充缺失值
问题:如果缺失了索引该怎么填充?
| 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 |
<matplotlib.axes._subplots.AxesSubplot at 0x1a0d908bf48>
问题,这里缺失了2019-12-03的数据,导致数据不全该怎么补充?
方法1:使用pandas.reindex方法
1、将df的索引变成日期索引
| pv | uv |
---|
pdate | | |
---|
2019-12-01 | 100 | 10 |
2019-12-02 | 200 | 20 |
2019-12-04 | 400 | 40 |
2019-12-05 | 500 | 50 |
Index(['2019-12-01', '2019-12-02', '2019-12-04', '2019-12-05'], dtype='object', name='pdate')
| pv | uv |
---|
pdate | | |
---|
2019-12-01 | 100 | 10 |
2019-12-02 | 200 | 20 |
2019-12-04 | 400 | 40 |
2019-12-05 | 500 | 50 |
DatetimeIndex(['2019-12-01', '2019-12-02', '2019-12-04', '2019-12-05'], dtype='datetime64[ns]', name='pdate', freq=None)
2、使用pandas.reindex填充缺失的索引
DatetimeIndex(['2019-12-01', '2019-12-02', '2019-12-03', '2019-12-04',
'2019-12-05'],
dtype='datetime64[ns]', freq='D')
| pv | uv |
---|
2019-12-01 | 100 | 10 |
2019-12-02 | 200 | 20 |
2019-12-03 | 0 | 0 |
2019-12-04 | 400 | 40 |
2019-12-05 | 500 | 50 |
<matplotlib.axes._subplots.AxesSubplot at 0x1a0db1ab388>
方法2:使用pandas.resample方法
1、先将索引变成日期索引
| 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 |
| pv | uv |
---|
pdate | | |
---|
2019-12-01 | 100 | 10 |
2019-12-02 | 200 | 20 |
2019-12-04 | 400 | 40 |
2019-12-05 | 500 | 50 |
DatetimeIndex(['2019-12-01', '2019-12-02', '2019-12-04', '2019-12-05'], dtype='datetime64[ns]', name='pdate', freq=None)
2、使用dataframe的resample的方法按照天重采样
resample的含义:
改变数据的时间频率,比如把天数据变成月份,或者把小时数据变成分钟级别
resample的语法:
(DataFrame or Series).resample(arguments).(aggregate function)
resample的采样规则参数:
https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases
| pv | uv |
---|
pdate | | |
---|
2019-12-01 | 100.0 | 10.0 |
2019-12-02 | 200.0 | 20.0 |
2019-12-03 | 0.0 | 0.0 |
2019-12-04 | 400.0 | 40.0 |
2019-12-05 | 500.0 | 50.0 |
| pv | uv |
---|
pdate | | |
---|
2019-12-01 | 150.0 | 15.0 |
2019-12-03 | 200.0 | 20.0 |
2019-12-05 | 500.0 | 50.0 |