【问题标题】:How to plot time only of pandas datetime64[ns] attribute如何仅绘制熊猫 datetime64[ns] 属性的时间
【发布时间】:2021-02-19 03:31:47
【问题描述】:

我有一个格式为 datetime64[ns] 的长时间范围的数据框和一个 int 值

数据如下所示:

                  MIN_DEP  DELAY
0     2018-01-01 05:09:00      0
1     2018-01-01 05:13:00      0
2     2018-01-01 05:39:00      0
3     2018-01-01 05:43:00      0
4     2018-01-01 06:12:00     34
...                   ...    ...
77005 2020-09-30 23:42:00      0
77006 2020-09-30 23:43:00      0
77007 2020-09-30 23:43:00     43
77008 2020-10-01 00:18:00      0
77009 2020-10-01 00:59:00      0

[77010 rows x 2 columns]
MIN_DEP    datetime64[ns]
DELAY               int64
dtype: object

目标是在 x 轴上仅绘制 00:00 - 24:00 范围内的所有数据,不再有日期。

当我尝试绘制它时,时间线在任何时候都是 00:00。如何解决这个问题?

import matplotlib.dates as mdates

fig, ax = plt.subplots()
ax.plot(pd_to_stat['MIN_DEP'],pd_to_stat['DELAY'])

xfmt = mdates.DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(xfmt)

plt.show()

尝试将之前的时间戳转换为 dt.time 然后绘制它

pd_to_stat['time'] = pd.to_datetime(pd_to_stat['MIN_DEP'], format='%H:%M').dt.time
fig, ax = plt.subplots()
ax.plot(pd_to_stat['time'],pd_to_stat['DELAY'])
plt.show()

情节不允许这样做:

TypeError: float() argument must be a string or a number, not 'datetime.time'

【问题讨论】:

    标签: python pandas datetime plot


    【解决方案1】:

    根据您的要求,我猜您不需要时间戳中的日期和秒字段。所以你首先需要一点预处理。 使用下面的代码删除秒字段

    dataset['MIN_DEP'] = dataset['MIN_DEP'].strftime("%H:%M")
    

    然后您可以通过以下方式从时间戳中删除日期

    dataset['MIN_DEP'] = pd.Series([val.time() for val in dataset['MIN_DEP']])
    

    然后你可以用通常的方式绘制你的数据。

    【讨论】:

    • 谢谢!但情节仍然说TypeError: float() argument must be a string or a number, not 'datetime.time'
    • 您能否在使用我的解决方案后打印数据集的类型['MIN_DEP'] 并提及之后的数据类型是什么。
    • Type 是 MIN_DEP object 实际上您的解决方案与我在帖子末尾提到的 pd_to_stat['time'] = pd.to_datetime(pd_to_stat['MIN_DEP'], format='%H:%M').dt.time 完全相同。
    【解决方案2】:

    这似乎现在有效。我没有认出,情节仍在日期分裂。为了解决这个问题,我可以用相同的日期替换所有日期并使用 DateFormatter 隐藏日期

    import matplotlib.dates as mdates
    pd_to_stat['MIN_DEP'] = pd_to_stat['MIN_DEP'].map(lambda t: t.replace(year=2020, month=1, day=1))
    
    fig, ax = plt.subplots()
    ax.plot(pd_to_stat['MIN_DEP'],pd_to_stat['DELAY'])
    
    xfmt = mdates.DateFormatter('%H:%M')
    ax.xaxis.set_major_formatter(xfmt)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-19
      • 2015-04-07
      • 1970-01-01
      • 2014-06-25
      • 2020-05-18
      • 2022-07-21
      • 2019-05-02
      • 2016-10-18
      相关资源
      最近更新 更多