Using Pandas dataframe to group data by dates and then hours

Viewed 75

I am working with a pandas dataframe where I would like to group the first five days and last five days together. Then from that grouping, I'd like to average the sample measurement from the same hour. ie: Of those 10 days, sample measurements from 00:00:00 averaged. Any guidance on how to achieve this would be much appreciated. Thank you.

Datetime Sample Measurement
2019-08-17 00:00:00 10
2019-08-17 01:00:00 14
2019-08-17 02:00:00 12
2019-08-17 03:00:00 10
..... ....
2019-09-07 20:00:00 9
2019-09-07 21:00:00 7
2019-09-07 22:00:00 5
2019-09-07 23:00:00 3
1 Answers

First you will need to change the DateTime column to date time object using pandas.to_datetime method

then make a new column with date only for example:

 df['date_only'] = df['Datetime'].dt.date 

would work in your case

then use pandas groupby and mean methods to group all similar dates together and then take the mean of their sample measurement

for ex:

df.groupby(['date_only'])['Sample Measurement'].mean()

would work

Related