2013-02-14 54 views
2

我正在读取文件中的一些csv日志数据,并使用日期,时间字段作为帧的索引。当我绘制时间序列时,绝对时间显示在X轴上。我想在x轴上显示相对于开始时间的时间。这个怎么做?熊猫时间序列相对于开始的使用时间

例如:这里是一个示例x轴:

23:59:57--------+23:59:58----------23:59:59--------+00:00:00--------------+ 

我希望它是这样的:

0---------00:00:01----------00:00:02--------+00:00:03--------------+ 

回答

3

一个简单的解决方案是从索引中减去所述第一索引项目。它可以通过使用列表理解来完成,如果你的数据帧非常大,这可能不是最好的(最快)选项。

begin = pd.datetime(2013,1,5,5,53) 
end = pd.datetime(2013,1,7,7,16) 

rng = pd.DatetimeIndex(start=begin, end=end, freq=pd.datetools.Minute(15)) 
df = pd.DataFrame(np.random.randn(rng.size), index=rng) 

fig, axs = plt.subplots(2,1, figsize=(15,6)) 
fig.subplots_adjust(hspace=.5) 

df.plot(ax=axs[0]) 
axs[0].set_title('Original') 

df.index = [idx - df.index[0] for idx in df.index] 
df.plot(ax=axs[1]) 
axs[1].set_title('Normalized') 

enter image description here

+0

太好了,谢谢。在从csv:df.date_time = df.date_time - df.date_time [0]中读取数据帧后,我尝试了类似的方法,该错误信息出错说''Timestamp'对象没有属性'dtype'“。我现在会尝试你的解决方案。 – 2013-02-14 18:04:56

+0

@Rutger_Kassies我看到,做df.index = [idx - df.index [0] for idx in df.index]将索引的数据类型更改为Objects而不是DatetimeIndex,它正在更改图形输出。我会将输出图像作为单独的答案发布,以便您了解正在发生的事情。如果您有任何线索,我会调查自己修复此问题,但在此发布。 – 2013-03-05 20:16:16

2

Here is the output after I did relative time normalization

由于索引的数据类型从DatetimeIndex改变为目的,正在打印在单独的存储桶的每一行。

+1

现在通过这样做修复问题:start_t = pd.tslib.Timestamp(df.index [0] .date())df.index = [pd.tslib.Timestamp(start_t +(idx - df.index [0]) )为df.index中的idx] – 2013-03-05 22:56:06