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

How to calculate the SUM of time in hh:mi format in pandas dataframe

I have a pandas data frame like this:

enter image description here

how can i calculate the SUM of total time per group? the time format is in HH:MI.
for example for G1 we’ve total (01:30+02:30+05:30)=09:30.
I’ve checked many solutions like separating each item via ":" by for loop or multiplying it *60 but no success.

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

>Solution :

You can convert each value to Timedelta than sum them:

df['SUM'] = pd.to_timedelta(df['HOURS'].str.split(',').explode() + [':00']) \
              .groupby(level=0).sum()
print(df)

# Output
  GROUP              HOURS             SUM
0    G1  01:30,02:30,05:30 0 days 09:30:00
1    G2  02:30,05:30,07:30 0 days 15:30:00
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