Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas timeseries use time relative to beginning

Tags:

python

pandas

I am reading some csv log data from a file and using the date,time fields as the index of the frame. When I plot the timeseries, the absolute times are shown in X-axis. I want to show the time on x-axis relative to the start time. How to do this?

For example: here is a sample x-axis:

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

I want it like this:

 0---------00:00:01----------00:00:02--------+00:00:03--------------+
like image 623
nom-mon-ir Avatar asked Oct 27 '25 08:10

nom-mon-ir


2 Answers

An easy solution is to subtract the first index-item from the index. It can be done by using list comprehension, which might not be the best (fastest) option if your Dataframe very large.

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

like image 117
Rutger Kassies Avatar answered Oct 29 '25 21:10

Rutger Kassies


Here is the output after I did relative time normalization

Since the data type of the indices changed from DatetimeIndex to objects, each line is being printed in separate buckets.

like image 38
nom-mon-ir Avatar answered Oct 29 '25 23:10

nom-mon-ir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!