Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hh:mm:ss to minutes using python pandas

Tags:

python

pandas

I have a dataframe column, data['time taken'] ;

02:08:00
02:05:00
02:55:00
03:42:00
01:12:00
01:46:00
03:22:00
03:36:00

How do I get the output in the form of minutes like below?

128
125
175
222
72
106
202
216
like image 631
richie Avatar asked Jul 30 '13 15:07

richie


2 Answers

Assuming this is a string column you can use the str.split method:

In [11]: df['time taken'].str.split(':')
Out[11]:
0    [02, 08, 00]
1    [02, 05, 00]
2    [02, 55, 00]
3    [03, 42, 00]
4    [01, 12, 00]
5    [01, 46, 00]
6    [03, 22, 00]
7    [03, 36, 00]
Name: time taken, dtype: object

And then use apply:

In [12]: df['time taken'].str.split(':').apply(lambda x: int(x[0]) * 60 + int(x[1]))
Out[12]:
0    128
1    125
2    175
3    222
4     72
5    106
6    202
7    216
Name: time taken, dtype: int64
like image 81
Andy Hayden Avatar answered Nov 13 '22 15:11

Andy Hayden


You could try to convert it to DatetimeIndex

In [58]: time = pd.DatetimeIndex(df['time taken'])

In [59]: time.hour * 60 + time.minute
Out[59]: array([128, 125, 175, 222,  72, 106, 202, 216], dtype=int32)
like image 12
waitingkuo Avatar answered Nov 13 '22 15:11

waitingkuo