Skip to content Skip to sidebar Skip to footer

How To Apply Lambda Function To Timestamp Column In Pandas Dataframe

I have dataframe with a timestamp column and iam using lambda function to that column. When i am doing that i am getting the following error: row['date'] = pd.Timestamp(row['date']

Solution 1:

It seems you need to_datetime for convert column to datetimes instead Timestamp - it convert only scalar:

row['date']=pd.to_datetime(row['date']).apply(lambda t: t.replace(minute=15*(t.minute//15)))
                .dt.strftime('%H:%M')

EDIT:

print (df)
       a      b
0  05:06  05:00
1  05:20  05:15
2  09:18  09:15
3  10:03  10:00

df['date'] = pd.to_datetime(df['a'])
               .apply(lambda t: t.replace(minute=15*(t.minute//15)))
               .dt.strftime('%H:%M')

print (df)
       a      b   date
0  05:06  05:00  05:00
1  05:20  05:15  05:15
2  09:18  09:15  09:15
3  10:03  10:00  10:00

Another solution but with different output:

df['date'] = pd.to_datetime(df['a']).dt.round('15min').dt.strftime('%H:%M')

For checking output you can use:

L = ['5:' + str(x).zfill(2) for x in range(60)]
df = pd.DataFrame({'a':L})
#print (df)df['date1'] = pd.to_datetime(df['a']).dt.round('15min').dt.strftime('%H:%M')
df['date'] = pd.to_datetime(df['a'])
               .apply(lambda t: t.replace(minute=15*(t.minute//15)))
               .dt.strftime('%H:%M') 
print (df)
       a  date1   date
0   5:00  05:00  05:00
1   5:01  05:00  05:00
2   5:02  05:00  05:00
3   5:03  05:00  05:00
4   5:04  05:00  05:00
5   5:05  05:00  05:00
6   5:06  05:00  05:00
7   5:07  05:00  05:00
8   5:08  05:15  05:00
9   5:09  05:15  05:00
10  5:10  05:15  05:00
11  5:11  05:15  05:00
12  5:12  05:15  05:00
13  5:13  05:15  05:00
14  5:14  05:15  05:00
15  5:15  05:15  05:15
16  5:16  05:15  05:15
17  5:17  05:15  05:15
18  5:18  05:15  05:15
19  5:19  05:15  05:15
20  5:20  05:15  05:15
21  5:21  05:15  05:15
22  5:22  05:15  05:15
23  5:23  05:30  05:15
24  5:24  05:30  05:15
25  5:25  05:30  05:15
26  5:26  05:30  05:15
27  5:27  05:30  05:15
28  5:28  05:30  05:15
29  5:29  05:30  05:15
30  5:30  05:30  05:30
31  5:31  05:30  05:30
32  5:32  05:30  05:30
33  5:33  05:30  05:30
34  5:34  05:30  05:30
35  5:35  05:30  05:30
36  5:36  05:30  05:30
37  5:37  05:30  05:30
38  5:38  05:45  05:30
39  5:39  05:45  05:30
40  5:40  05:45  05:30
41  5:41  05:45  05:30
42  5:42  05:45  05:30
43  5:43  05:45  05:30
44  5:44  05:45  05:30
45  5:45  05:45  05:45
46  5:46  05:45  05:45
47  5:47  05:45  05:45
48  5:48  05:45  05:45
49  5:49  05:45  05:45
50  5:50  05:45  05:45
51  5:51  05:45  05:45
52  5:52  05:45  05:45
53  5:53  06:00  05:45
54  5:54  06:00  05:45
55  5:55  06:00  05:45
56  5:56  06:00  05:45
57  5:57  06:00  05:45
58  5:58  06:00  05:45
59  5:59  06:00  05:45

Post a Comment for "How To Apply Lambda Function To Timestamp Column In Pandas Dataframe"