jam
jam

Reputation: 567

Change datetime axis in pandas?

I have made a plot with the following datetime axis.

enter image description here

How can I change it such that is begins at 6AM and ends at 3AM (instead of beginning at 7pm and ending at 4pm)? If it's relevant, this is how I am making the plot:

df.plot(df.sttm, legend=False)

where df is pandas dataframe.

Upvotes: 0

Views: 334

Answers (1)

Nickil Maveli
Nickil Maveli

Reputation: 29711

Use tshift method that changes all the dates in the index by a specified number of offsets.(Assumes that the index is a datetime object).

Demo:

from datetime import datetime
index = pd.date_range(start=datetime(2016,10,6,19), end=datetime(2016,10,7,16), freq='3H')
df = pd.DataFrame(np.random.randint(0,10, (8,1)), index=index)
df.index

gives:

DatetimeIndex(['2016-10-06 19:00:00', '2016-10-06 22:00:00',
               '2016-10-07 01:00:00', '2016-10-07 04:00:00',
               '2016-10-07 07:00:00', '2016-10-07 10:00:00',
               '2016-10-07 13:00:00', '2016-10-07 16:00:00'],
              dtype='datetime64[ns]', freq='3H')

Selecting an offfset to create the lag.

df.tshift(-13, freq='H').index

gives:

DatetimeIndex(['2016-10-06 06:00:00', '2016-10-06 09:00:00',
               '2016-10-06 12:00:00', '2016-10-06 15:00:00',
               '2016-10-06 18:00:00', '2016-10-06 21:00:00',
               '2016-10-07 00:00:00', '2016-10-07 03:00:00'],
              dtype='datetime64[ns]', freq='3H')

This keeps the column values as it is and does not produce any shift in them. It simply alters(shifts) the index axis.

Upvotes: 1

Related Questions