问题:按日期统计的数据,缺失了某天,导致数据不全该怎么补充日期?
1、数据准备
import pandas as pd
import matplotlib.pyplot as plt #画图需要的包
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],
})
print(df)
df.set_index("pdate").plot()
plt.show()
![](https://img.haomeiwen.com/i15616481/36a19c88ef052158.png)
![](https://img.haomeiwen.com/i15616481/72aaf5e0bf65db26.png)
可以用两种方法实现:
一、DataFrame.reindex,调整dataframe的索引以适应新的索引
1、将df的索引变成日期索引
df_date = df.set_index("pdate")
print(df_date.index)
df_date = df_date.set_index(pd.to_datetime(df_date.index))
print(df_date.index)
![](https://img.haomeiwen.com/i15616481/9dc6b6fa8ddf57bd.png)
2、使用pandas.reindex填充缺失的索引
#设置连续日期索引
pdates = pd.date_range(start="2019-12-01", end="2019-12-05")
print(pdates)
df_date_new = df_date.reindex(pdates, fill_value=0)
print(df_date_new)
df_date_new.plot()
plt.show()
![](https://img.haomeiwen.com/i15616481/2d5215045f8e875e.png)
![](https://img.haomeiwen.com/i15616481/803b3d18307f9ea6.png)
二、DataFrame.resample,可以对时间序列重采样,支持补充缺失值
1、将索引变成日期索引
df_new2 = df.set_index(pd.to_datetime(df["pdate"])).drop("pdate", axis=1)
print(df_new2)
![](https://img.haomeiwen.com/i15616481/5ffc51b536e11390.png)
2、使用dataframe的resample的方法按照天重采样
resample的含义:
改变数据的时间频率,比如把天数据变成月份,或者把小时数据变成分钟级别
resample的语法:
(DataFrame or Series).resample(arguments).(aggregate function)
https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases
#reresample的参数代表天,具体使用可参照上面的链接
df_new2 = df_new2.resample("D").mean().fillna(0)
print(df_new2)
![](https://img.haomeiwen.com/i15616481/1db99493b22b1b25.png)
df_new3 = df_new2.resample("2D").mean()
print(df_new3)
![](https://img.haomeiwen.com/i15616481/911c53afa9b5bfa5.png)
网友评论