【问题标题】:plot score against timestamp in pandas在熊猫中根据时间戳绘制分数
【发布时间】:2019-05-02 14:00:26
【问题描述】:

我在 pandas 中有一个数据框:

date_hour   score
2019041822  -5
2019041823  0
2019041900  6
2019041901  -5

其中 date_hour 是 YYYYMMDDHH 格式,而 score 是一个 int。

当我绘制时,有一条长线将 2019041823 连接到 2019041900,将其间的所有值视为不存在(即,没有与 2019041824-2019041899 相关的分数,因为没有时间与之相关)。

有没有办法忽略这些差距/absetvalues,以便它是连续的(我的一些数据错过了 2 天,所以我有一条很长的线路,这是误导性的)

红色圆圈表示夜晚之间的间隔(即 2300 年 4 月 18 日和 0000 年 4 月 19 日之间)。

我用过:

fig, ax = plt.subplots()
x=gpb['date_hour']
y=gpb['score']
ax.plot(x,y, '.-')
display(fig)

我相信这是因为 date_hours 是一个 int,并试图转换为 str,但遇到了错误:ValueError: x and y must have same first dimension

有没有办法绘制没有间隙?

【问题讨论】:

  • 在情节之前尝试df.date_hour = pd.to_datetime(df.date_hour, format='%Y%m%d%H')
  • 我会认真考虑单独加载matplotlib 进行绘图。也请在 stackoverflow 和 google 搜索关于绘制日期时间轴的无数线程。以this为例。

标签: pandas matplotlib plot


【解决方案1】:

尝试在绘图前将date_hour 转换为时间戳:df.date_hour = pd.to_datetime(df.date_hour, format='%Y%m%d%H')

df = pd.DataFrame({'date_hour':[2019041822, 2019041823, 2019041900, 2019041901],
                   'score':[-5,0,6,-5]})
df.date_hour = pd.to_datetime(df.date_hour, format='%Y%m%d%H')

df.plot(x='date_hour', y='score')
plt.show()

输出:

如果您不想更改数据,可以这样做

df = pd.DataFrame({'date_hour':[2019041822, 2019041823, 2019041900, 2019041901],
                   'score':[-5,0,6,-5]})

plt.plot(pd.to_datetime(df.date_hour, format='%Y%m%d%H'), df.score)

给出:

【讨论】:

  • 喜欢它,只是不确定如何解释我的集合中的空数据(4 月 21 日没有数据)-我的示例中的第二个红色圆圈
猜你喜欢
  • 1970-01-01
  • 2017-12-19
  • 2023-02-13
  • 2017-09-26
  • 2019-04-20
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多