Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round date time index in a pandas data frame?

There is a pandas dataframe like this:

index
2018-06-01 02:50:00     R 45.48 -2.8 
2018-06-01 07:13:00     R 45.85 -2.0  
... 
2018-06-01 08:37:00     R 45.87  -2.7

I would like to round the index to the hour like this:

index
2018-06-01 02:00:00     R 45.48 -2.8 
2018-06-01 07:00:00     R 45.85 -2.0  
... 
2018-06-01 08:00:00     R 45.87  -2.7

I am trying the following code:

df = df.date_time.apply ( lambda x : x.round('H'))

but returns a serie instead of a dataframe with the modified index column

like image 685
kamome Avatar asked Sep 06 '18 09:09

kamome


2 Answers

Try using floor:

df.index.floor('H')

Setup:

df = pd.DataFrame(np.arange(25),index=pd.date_range('2018-01-01 01:12:50','2018-01-02 01:12:50',freq='H'),columns=['Value'])
df.head()
                    Value
2018-01-01 01:12:50 0
2018-01-01 02:12:50 1
2018-01-01 03:12:50 2
2018-01-01 04:12:50 3
2018-01-01 05:12:50 4

df.index = df.index.floor('H')
df.head()
                    Value
2018-01-01 01:00:00 0
2018-01-01 02:00:00 1
2018-01-01 03:00:00 2
2018-01-01 04:00:00 3
2018-01-01 05:00:00 4
like image 195
Space Impact Avatar answered Sep 23 '22 17:09

Space Impact


Try my method:

Add a new column by the rounded value of hour:

df['E'] = df.index.round('H')

Set it as index:

df1 = df.set_index('E')

Delete the name you set('E' here):

df1.index.name = None

And now, df1 is a new DataFrame with index hour rounded from df.

like image 38
iPrince Avatar answered Sep 24 '22 17:09

iPrince