1

For the following dataframe "Schedule", how does one create the column "Hour_Number" from the column Time_Stamp which lists the time in HH:MM or H:MM format?

Output:

     Time_Stamp    Hour_Number
  0  11:16         11
  1  14:19         14
  2  13:02         13
  3  2:12          2
  4  7:15          7
cs95
  • 379,657
  • 97
  • 704
  • 746
beluga217
  • 41
  • 1
  • 4

1 Answers1

4

Use str.split to split on colon, and then extract the first item with the .str accessor:

df['Hour_Number'] = df.Time_Stamp.str.split(':').str[0].astype(int)

An alternative would be a conversion to datetime using to_datetime and then extracting the hour component:

df['Hour_Number'] = pd.to_datetime(df.Time_Stamp).dt.hour

df
  Time_Stamp  Hour_Number
0      11:16           11
1      14:19           14
2      13:02           13
3       2:12            2
4       7:15            7
cs95
  • 379,657
  • 97
  • 704
  • 746