【问题标题】:TypeError: strptime() argument 1 must be string, not floatTypeError:strptime() 参数 1 必须是字符串,而不是浮点数
【发布时间】: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


【解决方案1】:

要使用 matplotlib 绘制相关数据框,您可以先使用 pandas.to_datetime 将相关列转换为日期时间。

u = u"""i         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"""

import io
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(io.StringIO(u), delim_whitespace=True)
df["event"] = pd.to_datetime(df["event"], format="%d/%m/%Y")

plt.plot(df["event"], df["value_1"])
plt.gcf().autofmt_xdate()
plt.show()

【讨论】:

  • 谢谢,pd.to_datetime这个命令我之前没遇到过,会很有用的。
猜你喜欢
  • 2021-07-11
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 2022-01-09
  • 2015-12-03
  • 2013-12-30
相关资源
最近更新 更多