【问题标题】:convert time (without date) to Matplotlib num with date2num()使用 date2num() 将时间(无日期)转换为 Matplotlib num
【发布时间】:2019-04-08 09:05:37
【问题描述】:

我有一个这样的数据框 df:

        datetime          duration
0   2018-10-08 13:30:00    03:00
1   2018-10-08 16:40:00    00:11
2   2018-10-08 21:30:00    03:19
3   2018-10-09 03:21:00    04:27
4   2018-10-09 07:49:00    02:11

两种类型的两列都是 pandas.core.series.Series 为:

In[20]:  type(df_sleep['datetime'])
Out[20]: pandas.core.series.Series

In[21]:  type(df_sleep['duration'])
Out[20]: pandas.core.series.Series

我想用下面的方法来转换数据:

import matplotlib.dates as dates
dates.date2num(df_sleep['datetime'])
dates.date2num(df_sleep['duration'])

虽然“日期时间”列有效,但“持续时间”列显示以下错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-3720cbfdbdfa> in <module>()
----> 1 dates.date2num(df_sleep['duration'])

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in date2num(d)
    450         if not d.size:
    451             return d
--> 452         return _to_ordinalf_np_vectorized(d)
    453 
    454 

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/lib/function_base.py in __call__(self, *args, **kwargs)
   2753             vargs.extend([kwargs[_n] for _n in names])
   2754 
-> 2755         return self._vectorize_call(func=func, args=vargs)
   2756 
   2757     def _get_ufunc_and_otypes(self, func, args):

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/lib/function_base.py in _vectorize_call(self, func, args)
   2823             res = func()
   2824         else:
-> 2825             ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
   2826 
   2827             # Convert args to object arrays first

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/lib/function_base.py in _get_ufunc_and_otypes(self, func, args)
   2783 
   2784             inputs = [arg.flat[0] for arg in args]
-> 2785             outputs = func(*inputs)
   2786 
   2787             # Performance note: profiling indicates that -- for simple

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in _to_ordinalf(dt)
    253         tzi = UTC
    254 
--> 255     base = float(dt.toordinal())
    256 
    257     # If it's sufficiently datetime-like, it will have a `date()` method

AttributeError: 'str' object has no attribute 'toordinal'

有人知道吗?我的最终目标是使用 Matplotlib 在“日期时间”(x 轴)-“持续时间”(y 轴)中绘制数据。我猜这是因为 df['duration'] 列仅包含时间但不包含日期,并且不能做转换?我该怎么做才能进行绘图?

非常感谢您的任何建议!

【问题讨论】:

  • 请不要显示代码、数据或错误消息或其他任何图像。你的代码在哪里? “function dates.date2num”可能会告诉我,您导入了 matplotlib.dates,但这里没有人想玩猜谜游戏...请将您的代码发布为文本,格式正确的代码(选择然后 Ctrl+k)和相同与您的数据。
  • 嗨@SpghttCd 很抱歉这个问题很混乱,我已经对其进行了编辑并使其易于理解。非常感谢您指出这一点。
  • 我的第一个提示是:不要询问数据框列的类型 - 它始终是一个系列。有趣的类型是列元素的类型,即type(df_sleep['datetime'][0])`的输出。我猜在 datetime 中有 datetime 值,但在 duration 中有字符串。
  • 你的持续时间是什么意思?是 HH:MM 还是 MM:SS?
  • @SpghttCd 非常感谢,我对此仍然很原始。非常感谢您的帮助,为我节省大量时间!!!

标签: python pandas matplotlib


【解决方案1】:

猜你的持续时间格式是 %H:%M。首先,将列格式更改为日期时间。

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, date2num

df['datetime'] = pd.to_datetime(df.datetime)
df["duration"] = pd.to_datetime(df["duration"],format="%H:%M")

fig, ax = plt.subplots()

myFmt = DateFormatter("%H:%M:%S")
ax.yaxis.set_major_formatter(myFmt)

ax.plot(df['datetime'], df['duration'])

plt.gcf().autofmt_xdate()

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 2017-01-30
    • 2016-04-22
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多