带有时间戳的熊猫图

时间:2019-05-29 15:32:07

标签: python-3.x pandas

熊猫0.23.4 python 3.5.3

我有一些类似于下面的代码

import pandas as pd
from datetime import datetime

from matplotlib import pyplot


def dateparse():
    return datetime.strptime("2019-05-28T00:06:20,927", '%Y-%m-%dT%H:%M:%S,%f')


series = pd.read_csv('sample.csv', delimiter=";", parse_dates=True,
                     date_parser=dateparse, header=None)
series.plot()
pyplot.show()

CSV文件如下所示

2019-05-28T00:06:20,167;2070
2019-05-28T00:06:20,426;147
2019-05-28T00:06:20,927;453
2019-05-28T00:06:22,688;2464
2019-05-28T00:06:27,260;216

如您所见,2019-05-28T00:06:20,167是带有毫秒的时间戳,而2070是我要绘制的值。

enter image description here

当我运行此图时,该图被打印出来,但是在X轴上看到的数字有些奇怪。我期望看到实际的时间戳(例如MS Excel)。有人可以告诉我我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

您没有将日期时间设置为索引。 Aslo,您不需要日期解析器,只需传递要解析的列即可:

dfstr = '''2019-05-28T00:06:20,167;2070
2019-05-28T00:06:20,426;147
2019-05-28T00:06:20,927;453
2019-05-28T00:06:22,688;2464
2019-05-28T00:06:27,260;216'''

df = pd.read_csv(pd.compat.StringIO(dfstr), sep=';', 
                 header=None, parse_dates=[0])


plt.plot(df[0], df[1])
plt.show()

输出:

enter image description here

或者:

df.set_index(0)[1].plot()

给出更好的情节:

enter image description here

相关问题