TypeError:strTime()参数1必须是字符串,n

2024-04-17 18:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

早上好!

我有一系列与日期相关的活动。事件日期以一系列字符串值的形式存储在我加载到Python中的dataframe列中。数据帧包含其他具有值的列。我想将“event”列中的值转换为datetime对象,将它们存储在一个列表中,然后使用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

关于我错在哪里的任何建议都将受到感激。


Tags: 数据对象字符串ineventdataframe列表datetime
1条回答
网友
1楼 · 发布于 2024-04-17 18:45:57

要使用matplotlib绘制有问题的数据帧,可以先使用pandas.to_datetime将有问题的列转换为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()

enter image description here

相关问题 更多 >

    热门问题