【发布时间】:2017-12-19 09:29:04
【问题描述】:
早上好!
我有一系列相关日期的事件。事件日期作为一系列字符串值存储在我已加载到 Python 中的数据框中的列中。数据框包含其他带有值的列。我想将“事件”列中的值转换为日期时间对象,将它们存储在一个列表中,然后用 matplotlib 绘制该列表以创建一个时间序列。
我的数据框如下所示:
date value_1 event other_event
37 07/02/2015 265.09 07/02/2015 NaN
38 08/02/2015 278.59 08/02/2015 NaN
156 06/06/2015 146.07 06/06/2015 NaN
180 30/06/2015 133.56 30/06/2015 NaN
243 01/09/2015 280.27 01/09/2015 01/09/2015
Python 告诉我列数据是Name: event, dtype: object,我认为这意味着它包含字符串值。我的代码中还有df.event.apply(str) 行,我认为它将我的事件列中的值转换为字符串值。
然后我有这个代码:
FMT = '%d/%m/%Y'
event_list = []
for i in range(0, len(event)):
event_list.append(datetime.datetime.strptime(event[i], FMT))
但是,这行返回错误:
Traceback (most recent call last):
File "<ipython-input-39-e778a465e858>", line 2, in <module>
event_list.append(datetime.datetime.strptime(event[i], FMT))
TypeError: strptime() argument 1 must be string, not float
我们将不胜感激地收到任何关于我哪里出错的建议。
【问题讨论】:
-
你的变量
event看起来怎么样? -
您能否进一步解释一下 - 您是指对象类型吗?它的一些值包含在我在 OP 中发布的数据框中。
-
len(event)和event[0]得到什么? -
对于
len('event'),我收到8,尽管手动计数我在该列中有50 个值。对于event[0],我收到NaN。
标签: python string datetime matplotlib strptime