Tacio Degrazia
Tacio Degrazia

Reputation: 65

Convert hours format to minutes (float) with Pandas

I'm following one tutorial for web scraping an I'm stuck with one part. I'm only getting errors when I try to run the following code:

df7['Time2'] =  df7['Time'].str.split(':').apply(lambda x: float(x[0]) * 60 + float(x[1]) + float(x[2])/60)

Get the error:

IndexError: list index out of range

Also tried the following:

time_mins = []
for i in time_list:
    h, m, s = i.split(':')
    math = (int(h) * 3600 + int(m) * 60 + int(s))/60
    time_mins.append(math)

Again didn't work.

My cell is like:

The format of current cell HH:MM:SS

The result that I want is like:

Objective output

Any help would be helpful... Tks in adv.

Upvotes: 1

Views: 2170

Answers (2)

Yugandhar
Yugandhar

Reputation: 601

data['Time2'] = data['Time'].apply(lambda x: sum([a*b for a,b in zip(list(map(int,x.split(':')))[::-1],[1/60,1,60])]))

If you have date['Time'] dtype as string if not then just make small change in above line :

x.str.split(':')

Upvotes: 0

Sayali Sonawane
Sayali Sonawane

Reputation: 12599

Create Sample Dataframe:

# Import packages
import pandas as pd
# Create sample dataframe 
time = ['1:38:17','1:38:31','1:38:32']
gender = ['M','F','M']
data = pd.DataFrame({
        'Time':time,
        'Gender':gender
        })

data
Out[]: 
      Time Gender
0  1:38:17      M
1  1:38:31      F
2  1:38:32      M

Convert column into timedelta format:

# Time conversion
data['Time'] = pd.to_timedelta(data['Time']) 
# Time in days 
data = data.assign(Time_in_days = [x.days for x in data['Time']])
# Time in hour
data = data.assign(Time_in_hour = [(x.seconds)/(60.0*60.0) for x in data['Time']] )
# Time in minutes 
data = data.assign(Time_in_minutes = [(x.seconds)/60.0 for x in data['Time']])
# Time in seconds
data = data.assign(Time_in_seconds = [x.seconds * 1.0 for x in data['Time']] )

print(data)

    Time   Gender  Time_in_days  Time_in_hour  Time_in_minutes  Time_in_seconds
0 01:38:17      M             0      1.638056        98.283333           5897.0
1 01:38:31      F             0      1.641944        98.516667           5911.0
2 01:38:32      M             0      1.642222        98.533333           5912.0

Upvotes: 1

Related Questions