I have df with column with time like this:
time
12:30
12:15
12:00
I need to have it in float type like this:
time
12.5
12.25
12.00
I have tried:
df.time = df.time.replace(":", ".", regex=True).astype(float)
but I have unsatisfactory result, like this:
time
12.3
12.15
12.00
Any idea please?
>Solution :
One solution is to use pandas.to_timedelta on a modified version of the input string (to match the expected format), then convert to total_seconds and divide by 60:
df['time_float'] = pd.to_timedelta('00:'+df['time']).dt.total_seconds()/60
output:
time time_float
0 12:30 12.50
1 12:15 12.25
2 12:00 12.00
Alternative using str.replace as you originally intended:
df['time'] = (df['time']
.str.replace('(:)(\d+)',
lambda x: f'.{100*int(x.group(2))//60}',
regex=True)
.astype(float)
)