Python: convert series object columns in pandas dataframe to int64 dtype

477 views Asked by At

I have the following data frame:

Day_Part     Start_Time    End_Time   
Breakfast    9:00          11:00
Lunch        12:00         14:00
Dinner       19:00         23:00

The columns Start_Time and End_time are 'Series Objects' right now. I want to convert the values in those columns into int64 dtype.

This is what I want the data frame to look like:

Day_Part     Start_Time    End_Time   
Breakfast    9             11
Lunch        12            14
Dinner       19            23

*Any help is greatly appreciated.

1

There are 1 answers

0
jezrael On BEST ANSWER

You can first convert to_timedelta and then extract hour:

df['Start_Time'] = pd.to_timedelta(df['Start_Time']+ ':00').dt.components.hours
df['End_Time'] = pd.to_timedelta(df['End_Time']+ ':00').dt.components.hours
print (df)

    Day_Part  Start_Time  End_Time
0  Breakfast           9        11
1      Lunch          12        14
2     Dinner          19        23

Another solution with split and cast to int:

df['Start_Time'] = df['Start_Time'].str.split(':').str[0].astype(int)
df['End_Time'] = df['End_Time'].str.split(':').str[0].astype(int)
print (df)

    Day_Part  Start_Time  End_Time
0  Breakfast           9        11
1      Lunch          12        14
2     Dinner          19        23

Solution with extract and cast to int:

df['Start_Time'] = df['Start_Time'].str.extract('(\d*):', expand=False).astype(int)
df['End_Time'] =  df['End_Time'].str.extract('(\d*):', expand=False).astype(int)
print (df)

    Day_Part  Start_Time  End_Time
0  Breakfast           9        11
1      Lunch          12        14
2     Dinner          19        23

Solution with convert to_datetime:

df['Start_Time'] = pd.to_datetime(df['Start_Time'], format='%H:%M').dt.hour
df['End_Time'] = pd.to_datetime(df['End_Time'], format='%H:%M').dt.hour
print (df)
    Day_Part  Start_Time  End_Time
0  Breakfast           9        11
1      Lunch          12        14
2     Dinner          19        23

Timings:

#[300000 rows x 3 columns]
df = pd.concat([df]*100000).reset_index(drop=True)
print (df)

In [158]: %timeit pd.to_timedelta(df['Start_Time']+ ':00').dt.components.hours
1 loop, best of 3: 7.12 s per loop

In [159]: %timeit df['Start_Time'].str.split(':').str[0].astype(int)
1 loop, best of 3: 415 ms per loop

In [160]: %timeit df['Start_Time'].str.extract('(\d*):', expand=False).astype(int)
1 loop, best of 3: 654 ms per loop

In [166]: %timeit pd.to_datetime(df['Start_Time'], format='%H:%M').dt.hour
1 loop, best of 3: 1.26 s per loop