【问题标题】:Python - How to plot day and time in stringPython - 如何在字符串中绘制日期和时间
【发布时间】:2017-11-26 15:33:08
【问题描述】:

我有这个数据框

    user_date   user_time
0   Thu         07:32:20
1   Wed         21:10:38
2   Fri         21:32:55
3   Sat         11:57:36
4   Fri         22:37:41

如何用 x 是 user_time 来绘制这个数据框,范围是 24 小时,y 是 user_date。

同时,非常感谢您的关注和参与。

【问题讨论】:

  • 是来自 csv 的数据帧吗?

标签: python pandas matplotlib


【解决方案1】:

user_date 值有问题,因为如果使用strings 获取:

TypeError: Empty 'DataFrame': no numeric data to plot

一种可能的解决方案是将它们转换为ordered categorical 并按cat.codes 绘制。

同样情节timedelata没有实现,所以user_timestrftime转换为to_datetime再转换为strings:

days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
df['user_date'] = df['user_date'].astype('category', categories=days, ordered=True)

df['user_time1'] = pd.to_datetime(df['user_time']).dt.strftime('%H:%M:%S')
df['user_date1'] = df['user_date'].cat.codes

ax = df.plot(x='user_time1', y='user_date1')

#set max and min values of axis
#https://stackoverflow.com/a/43460067/2901002
ax.set_yticks(range(7))
ax.set_yticklabels(days)

【讨论】:

  • 嗨@jezrael,感谢您的帮助。我有这个错误: NameError: name 'ticker' is not defined 该图在数据框中缺少一些数据。如何保持user_time?我不想换到第二个。
  • 是的,这并不容易,但现在应该可以了。请检查解决方案。
  • 嗨,我遇到了这个错误:** _astype() 得到了一个意外的关键字参数 'ors' **。我使用 Python 3,但在删除 ors=True, categories =days 后一切正常!非常感谢@jezrael
  • 你觉得x轴吗?从 0 到 24?
  • 我的意思是,我希望你能帮我显示 user_time 的所有数据。如果我有 50 个 user_time 值,如何在绘图上显示该用户的所有 50 个值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 2013-10-04
  • 2018-07-16
  • 1970-01-01
相关资源
最近更新 更多