首页 > 解决方案 > 绘制日期时间索引

问题描述

我遇到了按日期数据框分组的错误: byDate = df.groupby('Date').count()

Date       Value      
2019-08-15 2
2019-08-19 1    
2019-08-23 7    
2019-08-28 4
2019-09-04 7
2019-09-09 2    

我知道type(df["Date"].iloc[0]) 返回datetime.date

我想以这样的方式绘制数据,那些没有可用值的日子显示为 0。我玩过 ax = sns.lineplot(x=byDate.index.fillna(0), y="Value", data=byDate) 但我只能得到这个输出,其中 y 轴表示一条线对于没有可用值的天数,不绘制为 0。

在此处输入图像描述

标签: pythonpandasgroup-bytimestampseaborn

解决方案


您是否尝试过创建一个新的 dataFrame 对象,该对象由从startDateendDate的所有日期索引,然后用 填充缺失的值0.0

输出看起来像:

dates = pd.to_datetime(['2019-08-15','2019-08-19','2019-08-23','2019-08-28','2019-09-04','2019-09-09']).date
byDate = pd.DataFrame({'Value':[2,1,7,4,7,2]},index=dates)

startDate = byDate.index.min()
endDate = byDate.index.max()
newDates = pd.date_range(startDate,endDate, periods=(endDate - startDate).days).date.tolist()
newDatesDf = pd.DataFrame( index=newDates)
newByDate = pd.concat([newDatesDf,byDate],1).fillna(0)

sns.lineplot(x=newByDate.index, y="Value", data=newByDate)

输出


推荐阅读