0

I have a column of time data in a dataframe and the time format is "1300", "0325","1005", and so on. Please see screenshot linked.

How do I convert it to AM or PM and save the value in a new column in the dataframe? For example, "1300" will be "Afternoon", and "1005" will be "Morning".?

time period
1300 Afternoon
0450 Morning
2300 Evening
1008 Morning
2309 Evening

I thought about treating each value in the column as a string and then write if statements: if the first two characters is, for example, "13, 14, 15, ....", then return "Afternoon". If the first two characters is, for example, "06, 07...., 10", return "Morning", and so on.

Is this the correct approach?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72

1 Answers1

3

A hack is to convert your time column to int then use pd.cut to bins your value:

bins = [0, 300, 1200, 1800, 2400]
labels = ['Evening', 'Morning', 'Afternoon', 'Evening']

df['period'] = pd.cut(df['time'].astype(int), bins=bins, labels=labels, ordered=False)
print(df)

# Output
   time     period
0  1300  Afternoon
1  0450    Morning
2  2300    Evening
3  1008    Morning
4  2309    Evening
Corralien
  • 109,409
  • 8
  • 28
  • 52