Skip to content
Advertisement

Pandas groupby datetime columns by periods

I have the following dataframe:

JavaScript

I would like to get for each row (e.g a,b,c,d …) the mean vale between specific hours. The hours are between 9-15, and I want to groupby period, for example to calculate the mean value between 09:00:00 to 11:00:00, between 11- 12, between 13-15 (or any period I decide to).

I was trying first to convert the columns values to datetime format and then I though it would be easier to do this:

JavaScript

but then I got the columns names with fake year “1900-01-01 09:00:00″…

And also, the columns headers type was object, so I felt a bit lost…

My end goal is to be able to calculate new columns with the mean value for each row only between columns that fall inside the defined time period (e.g 9-11 etc…)

Advertisement

Answer

If need some period, e.g. each 2 hours:

JavaScript

If need some custom periods is possible use cut:

JavaScript

And last use mean per columns, reason of NaNs columns is columns are categoricals:

JavaScript

For avoid NaNs columns convert columns names to strings:

JavaScript

EDIT: Solution above with timedeltas, because format HH:MM:SS:

JavaScript

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement