【问题标题】:Counts of rows per hour每小时行数
【发布时间】:2021-12-29 07:22:32
【问题描述】:

我正在探索共享单车数据。

我合并了两张表:一张包含共享单车数据,另一张包含天气数据。 “开始日期”列位于共享单车数据中。 “日期”列在天气数据中。

我想对每小时的 ID 计数进行分组,以便查看天气对自行车使用量的影响。

ID Start End Date Start Duration date rain temp wdsp
1754125 Eyre Square South Glenina 01 Jan 2019 00:17 00:15:02 01-jan-2019 00:00 0.0 9.9 4.0
1754170 Brown Doorway University Hospital Galway 01 Jan 2019 07:55 00:04:57 01-jan-2019 01:00 0.0 9.3 4.0
1754209 New Dock Street New Dock Street 01 Jan 2019 11:42 02:57:57 01-jan-2019 02:00 0.0 9.2 5.0
1754211 Claddagh Basin Merchants Gate 01 Jan 2019 11:50 00:02:43 01-jan-2019 03:00 0.0 9.1 5.0

我试过了:

data.groupby(['date','ID']).size()
data.groupby(['date','ID']).size().reset_index(name='counts')

但我真的不知道自己在做什么。任何帮助将不胜感激。

【问题讨论】:

    标签: pandas dataframe pandas-groupby data-science etl


    【解决方案1】:

    我假设您希望能够按 ID、日期和小时计算行数,因此您可以这样做:

    df['Date'] = df['Date Start'].dt.normalize()
    df['hour'] = df['Date Start'].apply(lambda x: x.hour)
    

    获取日期和完整时间:

         ID              Start                         End          Date Start  \
    0  1754125  Eyre Square South                     Glenina 2019-01-01 00:17:00   
    1  1754170      Brown Doorway  University Hospital Galway 2019-01-01 07:55:00   
    2  1754209    New Dock Street             New Dock Street 2019-01-01 11:42:00   
    3  1754211     Claddagh Basin              Merchants Gate 2019-01-01 11:50:00   
    
       Duration              date  rain  temp  wdsp       Date  hour  
    0  00:15:02  2019-01-01 00:00   0.0   9.9   4.0 2019-01-01     0  
    1  00:04:57  2019-01-01 01:00   0.0   9.3   4.0 2019-01-01     7  
    2  02:57:57  2019-01-01 02:00   0.0   9.2   5.0 2019-01-01    11  
    3  00:02:43  2019-01-01 03:00   0.0   9.1   5.0 2019-01-01    11  
    

    然后使用分组方式:

    df.groupby(['ID','Date','hour']).size()
    
    

    返回

    ID        Date        hour
    1754125  2019-01-01  0       1
    1754170  2019-01-01  7       1
    1754209  2019-01-01  11      1
    1754211  2019-01-01  11      1
    dtype: int64
    

    【讨论】:

    • 也许我最初的问题并不清楚。我想统计 2019 年每小时的自行车旅行次数。我在 2019 年有 27109 次自行车旅行,而在 2019 年有 8760 小时。
    【解决方案2】:

    我使用伦敦自行车骑行数据做了一个类似的项目。我在 csv 中解析_dates,然后使用时间戳作为索引并检索日期时间部分

    df=pd.read_csv('london_merged.csv', parse_dates=['timestamp'], index_col="timestamp")
    df['year'] = df.index.year
    df['hour'] = df.index.hour
    df['day_of_month'] = df.index.day
    df['day_of_week'] = df.index.dayofweek
    df['month'] = df.index.month
    df['date']=df.index.date
    print(df)
    
    filter=df['year']==2019
    df[filter].groupby(['hour']).size()
    

    【讨论】:

    • 也许我最初的问题并不清楚。我想统计 2019 年每小时的自行车旅行次数。我在 2019 年有 27109 次自行车旅行,而在 2019 年有 8760 小时。
    猜你喜欢
    • 2011-04-15
    • 2018-09-09
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多