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

Convert string hours to minute pd.eval

I want to convert all rows of my DataFrame that contains hours and minutes into minutes only.
I have a dataframe that looks like this:

df=
    time
0    8h30
1    14h07
2    08h30
3    7h50
4    8h0 
5    8h15
6    6h15

I’m using the following method to convert:

df['time'] = pd.eval(
    df['time'].replace(['h'], ['*60+'], regex=True))

Output

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

SyntaxError: invalid syntax

I think the error comes from the format of the hour, maybe pd.evalcant accept 08h30 or 8h0, how to solve this probleme ?

>Solution :

To avoid having to trim leading zeros, an alternative approach:

df[['h', 'm']] = df['time'].str.split('h', expand=True).astype(int)
df['total_min'] = df['h']*60 + df['m']

Result:

    time   h   m      total_min
0   8h30   8  30            510
1  14h07  14   7            847
2  08h30   8  30            510
3   7h50   7  50            470
4    8h0   8   0            480
5   8h15   8  15            495
6   6h15   6  15            375
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