Piyush Rastogi
Piyush Rastogi

Reputation: 13

How to categorize timestamp hours into day and night?

I was wondering how can we categorize timestamp column in a Data frame into Day and Night column on the basis of time?

I am trying to do so but unable to make a new column complete with the same number of entries.

d_call["time"] = d_call["timestamp"].apply(lambda x: x.time())

d_call["time"].head(1)
 0    17:10:52
 Name: time, dtype: object

def day_night(name):

    for i in name:

        if i.hour > 17: 
             return "night"

        else:
            return "day"

 day_night(d_call["time"])
 'day'

d_call["Day / Night"]= d_call["time"].apply(lambda x: day_night(x))

I want to get the entire series of the column but getting the first index only.

Upvotes: 0

Views: 2048

Answers (1)

Naga kiran
Naga kiran

Reputation: 4607

You can strip time to get the hour of timestamp and w.r.t hour you can assign your category, you can also use other conditions to put range of time

Considered df
0   2018-06-18 15:05:52.246
1   2018-05-24 21:44:07.903
2   2018-06-06 21:00:19.635
3   2018-05-24 21:44:37.883
4   2018-05-30 11:19:36.546
5   2018-05-25 11:16:07.969
6   2018-05-24 21:43:35.077
7   2018-06-07 18:39:00.258
Name: modified_at, dtype: datetime64[ns]

df['day/night'] = df.modified_at.apply(lambda x:'night'  if int(x.strftime('%H')) >19 else 'day')

Out:

0      day
1    night
2    night
3    night
4      day
5      day
6    night
7      day
Name: modified_at, dtype: object

Upvotes: 1

Related Questions