Round and Remove 3 digits Python Dataframe

Question:

i have the following Dataframe:
Dataframe

print (df)
               time
0  00:00:04.4052727
1     00:00:06.5798

and my goal is to round the microseconds to 2 digits and remove the other digits so there are only 2 digits.

All columns should then look like the first row:

print (df)
           time
0  00:00:04.405
1  00:00:06.580
Asked By: hubi3012

||

Answers:

You can remove last 3 digits (000) after convert values to HH:MM:SS.fffff format:

df['time'] = pd.to_datetime(df['time'])


df['time'] = df['time'].dt.round('100L').dt.strftime('%H:%M:%S.%f').str[:-3]
print (df)
           time
0  00:00:04.400
1  00:00:06.600

Another idea is round by 1 milisecond:

df['time'] = df['time'].dt.round('1ms')
print (df)
                     time
0 2022-12-12 00:00:04.405
1 2022-12-12 00:00:06.580


df['time'] = df['time'].dt.round('1ms').dt.strftime('%H:%M:%S.%f').str[:-3]
print (df)
           time
0  00:00:04.405
1  00:00:06.580

If need only truncate values use Series.dt.floor:

df['time'] = df['time'].dt.floor('1ms')

print (df)
                     time
0 2022-12-12 00:00:04.405
1 2022-12-12 00:00:06.579


df['time'] = df['time'].dt.floor('1ms').dt.strftime('%H:%M:%S.%f').str[:-3]
print (df)
           time
0  00:00:04.405
1  00:00:06.579
Answered By: jezrael
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.