Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas data frame with time column

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
              )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading