如何导入带有一列的csv文件作为timeformat hh:mm:ss并使用pandas将其绘制在x轴上?

时间:2017-10-26 19:50:13

标签: python pandas matplotlib

这就是我的csv文件数据的样子。

Time stamp     kW
09:41:12   5.412224215
09:41:22   5.057871807
09:41:32   5.357250571
09:41:42   5.427124444
09:41:52   5.485060159
09:42:02   4.942689557
09:42:19   4.914225079
09:42:29   5.032617133
09:42:39   5.131685175
09:42:49   61.05746329

我试图导入它并将其绘制为x_axis为hh:ss:ss。

这就是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import datetime as dt
headers = ["Time stamp", "kW"]
dataset = pd.read_csv('Wash_Data1.csv',sep = ";",names = headers)
dataset.plot()

X-axis doesnt display the x values. What i want is this format 09:42:49

1 个答案:

答案 0 :(得分:1)

In [28]: df = df.set_index(pd.to_timedelta(df['Time stamp']))

In [29]: df
Out[29]:
           Time stamp         kW
Time stamp
09:41:12     09:41:12   5.412224
09:41:22     09:41:22   5.057872
09:41:32     09:41:32   5.357251
09:41:42     09:41:42   5.427124
09:41:52     09:41:52   5.485060
09:42:02     09:42:02   4.942690
09:42:19     09:42:19   4.914225
09:42:29     09:42:29   5.032617
09:42:39     09:42:39   5.131685
09:42:49     09:42:49  61.057463

In [30]: ax = df[['kW']].plot()

In [33]: ax.set_xticklabels(df['Time stamp'])

In [34]: df.index.dtype
Out[34]: dtype('<m8[ns]')

In [35]: df.dtypes
Out[35]:
Time stamp     object
kW            float64
dtype: object

结果:

enter image description here