简体   繁体   中英

How to group rows by hour of day in Pandas dataframe?

I have a dataframe with following data:

        kwh              time
0   0.217413    2019-04-09 17:00:00+00:00

1   4.133414    2019-04-09 18:00:00+00:00

2   5.154745    2019-04-09 19:00:00+00:00

3   2.497526    2019-04-09 20:00:00+00:00

The data represents kwh per hour. I am trying to group by hour of the day so that I can display:

  hour of day   sumkwh
    0             4
    1             5
    2             3
    23            6

I have tried a few options, but currently stuck.

s = df.groupby(df.time.hour).sum()

---> AttributeError: 'Series' object has no attribute 'hour'

How could this be done?

try this code it my help:

import pandas as pd
data = [[0, 0.217413, "2019-04-09 17:00:00"], [1, 4.133414, "2019-04-09 18:00:00"], 
[2, 5.154745, "2019-04-09 19:00:00"], [3, 2.497526, "2019-04-09 20:00:00"]]
df = pd.DataFrame(data=data, index=[0, 1, 2, 3], columns=["indx", "kwh", "hour"])
times = pd.DataFrame(data=pd.to_datetime(df["hour"]), columns=["hour"])
df.groupby(times.hour).sum()

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