使用日期索引时间序列数据绘制x轴上的经过时间

时间:2017-01-06 14:10:21

标签: python pandas matplotlib time-series

在我的pandas数据框中,我的时间序列数据按绝对时间(日期格式YYYY-MM-DD HH24:MI:SS.nnnnn)索引:

2017-01-04 16:25:25.143493    58
2017-01-04 16:25:26.145494    62
2017-01-04 16:25:27.147495    57
2017-01-04 16:25:28.149496    51
2017-01-04 16:25:29.151497    61

如何绘制这些数据,使得我的图的x轴相对于我的第一个样本的时间戳,是某个秒间隔(例如,“0 10 20 30 40 50”)的增加值?我是否需要使用句号,或使用asfreq()转换为频率?或者我应该使用DateFormatter吗?

文档有点令人困惑,似乎没有任何好的例子 - 大多数时间序列示例似乎都围绕着粗略的间隔,例如几个月或几年。

2 个答案:

答案 0 :(得分:4)

您可以将datetimeindex转换为timedeltaindex然后绘制。

df.index = df.index - df.index[0]
df.plot()

答案 1 :(得分:1)

可能有一种内置方法可以做到这一点,但你可以通过在列表理解中减去日期时间并使用total_seconds()来实现你想要的东西:

# Generate a random timeseries
a = pd.Series(index=pd.date_range("20000101",freq="s",periods=50),data=np.random.randint(0,10,50))

# Create a new index by calculating relative difference between the datetimes.
# If you use total_seconds, you will convert datetimes into integers (which is what you wanted in your question)
new_index = [(i-a.index[0]) for i in a.index]

# Apply new index to the original Series
a.index = new_index

# plot the data
a.plot()