Dheeraj
Dheeraj

Reputation: 1202

Groupby every 2 hours data of a dataframe

I have a dataframe:

                    Time  T201FN1ST2010  T201FN1VT2010
1791 2017-12-26 00:00:00         854.69           0.87
1792 2017-12-26 00:20:00         855.76           0.87
1793 2017-12-26 00:40:00         854.87           0.87
1794 2017-12-26 01:00:00         855.51           0.87
1795 2017-12-26 01:20:00         856.35           0.86
1796 2017-12-26 01:40:00         856.13           0.86
1797 2017-12-26 02:00:00         855.84           0.85
1798 2017-12-26 02:20:00         856.58           0.85
1799 2017-12-26 02:40:00         856.37           0.85
1800 2017-12-26 03:00:00         855.35           0.86
1801 2017-12-26 03:20:00         855.68           0.86
1802 2017-12-26 03:40:00         855.45           0.85
1803 2017-12-26 04:00:00         855.50           0.85
1804 2017-12-26 04:20:00         855.84           0.85
1805 2017-12-26 04:40:00         856.47           0.85
1806 2017-12-26 05:00:00         855.29           0.86
1807 2017-12-26 05:20:00         855.45           0.87
1808 2017-12-26 05:40:00         855.80           0.86
1809 2017-12-26 06:00:00         854.93           0.88

i am trying to group every two hours of data using groupby but i couldn't able to do it.

i tried this:

last8.groupby(last8.Time.dt.Timedelta('2H'))

But i am getting an error like AttributeError: 'DatetimeProperties' object has no attribute 'Timedelta'.

can anybody suggest me the coreect way to do it?

Any help would be appreciated.

Upvotes: 3

Views: 2892

Answers (1)

jezrael
jezrael

Reputation: 862901

I think you need groupby + Grouper + some aggregate function:

df = last8.groupby(pd.Grouper(freq='2H', key='Time')).mean()

Or resample + some aggregate function:

df = last8.resample('2H', on='Time').mean()

Or use groupby + floor:

df = last8.groupby(last8.Time.dt.floor('2H')).mean()

print (df)
                     T201FN1ST2010  T201FN1VT2010
Time                                             
2017-12-26 00:00:00     855.551667       0.866667
2017-12-26 02:00:00     855.878333       0.853333
2017-12-26 04:00:00     855.725000       0.856667
2017-12-26 06:00:00     854.930000       0.880000

Upvotes: 10

Related Questions