简体   繁体   中英

How to return datetime group of categorised period into a new pandas column?

I have a pandas dataframe that looks like this:

Date               Interval     
31/8/20 9:22:07    Period 1
31/8/20 7:20:35    Period 9
31/8/20 7:18:24    Period 9
31/8/20 7:13:49    Period 10
31/8/20 7:07:05    Period 10
31/8/20 6:46:54    Period 11
31/8/20 0:26:16    Period 37
30/8/20 23:52:20   Period 39
30/8/20 23:50:04   Period 39

Which is generated by the following code:

# CONVERT TO DATETIME
df['Date'] = pd.to_datetime(df['Date'])

# SORT BY DATE VALUES
df = df.sort_values(by=['Date'], ascending=False)

# GROUP INTO 15 MINUTE INTERVALS
s = df.groupby(pd.Grouper(freq='15min', key='Date')).ngroup(ascending=False).add(1)
df['Interval'] = 'Period ' + s.astype(str)

I would like to add a new column into my dataframe to show the datetime interval by which the 'Period' values were generated. Such that my output should look like this:

Date               Interval     15_Min_Interval_Period_Belongs_To
31/8/20 9:22:07    Period 1     31/8/20 9:15:00
31/8/20 7:20:35    Period 9     31/8/20 7:15:00
31/8/20 7:18:24    Period 9     31/8/20 7:15:00
31/8/20 7:13:49    Period 10    31/8/20 7:00:00
31/8/20 7:07:05    Period 10    31/8/20 7:00:00
31/8/20 6:46:54    Period 11    31/8/20 6:45:00
31/8/20 0:26:16    Period 37    31/8/20 0:15:00
30/8/20 23:52:20   Period 39    30/8/20 23:45:00
30/8/20 23:50:04   Period 39    30/8/20 23:45:00

I've tried:

s2 = df.groupby(pd.Grouper(freq='15min', key='Interval')).get_group()

to no avail.

Thank you for your help.

Use Series.dt.floor :

df['15_Min_Interval_Period_Belongs_To'] = df['Date'].dt.floor('15Min')

print (df)
                 Date   Interval 15_Min_Interval_Period_Belongs_To
0 2020-08-31 09:22:07   Period 1               2020-08-31 09:15:00
1 2020-08-31 07:20:35   Period 9               2020-08-31 07:15:00
2 2020-08-31 07:18:24   Period 9               2020-08-31 07:15:00
3 2020-08-31 07:13:49  Period 10               2020-08-31 07:00:00
4 2020-08-31 07:07:05  Period 10               2020-08-31 07:00:00
5 2020-08-31 06:46:54  Period 11               2020-08-31 06:45:00
6 2020-08-31 00:26:16  Period 37               2020-08-31 00:15:00
7 2020-08-30 23:52:20  Period 39               2020-08-30 23:45:00
8 2020-08-30 23:50:04  Period 39               2020-08-30 23:45:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM