Brain_overflowed Brain_overflowed - 3 years ago 208
Python Question

Rounding to nearest min in a pandas dataframe

I want to round the hh:mm:ss values in my TimeStamp col of the dataframe so that the seconds are always 00

Dataset:

TimeStamp A B C
10:27:30 1.953036 2.110234 1.981548
10:28:30 1.973408 2.046361 1.806923
10:29:30 0.000000 0.000000 0.014881
10:30:30 2.567976 3.169928 3.479591


I tried:

df_sr4500.TimeStamp = np.asarray(np.round(df_sr4500.TimeStamp.values / np.timedelta64(1, 'm')), dtype='timedelta64[m]')


I get:

TimeStamp A B C
10:28:00 1.953036 2.110234 1.981548
10:28:00 1.973408 2.046361 1.806923
10:30:00 0.000000 0.000000 0.014881
10:30:00 2.567976 3.169928 3.479591


I would have it rather rounding one way for the middle value.
The next step for me is to resample every two min with mean

Please suggest if you have any better/easier way to do this. I am very new to pandas/numpy.

Answer Source

Add one nanosecond to each time and then round.

df['TimeStamp'] = (df['TimeStamp'] + pd.Timedelta(1)).dt.round('min')

0   10:28:00
1   10:29:00
2   10:30:00
3   10:31:00
Name: TimeStamp, dtype: timedelta64[ns]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download