MeiNan Zhu
MeiNan Zhu

Reputation: 1049

Convert hh:mm:ss to minutes return but return TypeError: 'float' object is not subscriptable

Original data in a dataframe look like below and I want to convert it to minutes:

0         03:30:00
1              NaN
2         00:25:00

I learned a very good approach from this post: Convert hh:mm:ss to minutes using python pandas

df2['FS_Runtime'].str.split(':') running this code split the data into below

0         [03, 30, 00]
1              NaN
2         [00, 25, 00]

I then added the .apply like the example in the post.

df2['FS_Runtime'].str.split(':').apply(lambda x: int(x[0])*60)

but i got the following error:

TypeError: 'float' object is not subscriptable

Upvotes: 1

Views: 170

Answers (2)

ALollz
ALollz

Reputation: 59549

Your format is in the proper format for pd.to_timedelta then get the number of seconds and divide by 60:

import pandas as pd
import numpy as np

pd.to_timedelta(df['FS_Runtime']).dt.total_seconds()/60
# Alternatively
pd.to_timedelta(df['FS_Runtime'])/np.timedelta64(1, 'm')

#0    210.0
#1      NaN
#2     25.0
#Name: FS_Runtime, dtype: float64

Upvotes: 1

Vaishali
Vaishali

Reputation: 38415

The issue is because of NaN in the dataframe. You can try this

df1['FS_Runtime'] = pd.to_datetime(df1['FS_Runtime'], format = '%H:%M:%S')
df1['FS_Runtime'].dt.hour * 60 + df1['FS_Runtime'].dt.minute

0    210.0
1      NaN
2     25.0

Upvotes: 2

Related Questions