【问题标题】:Resample timestamps hourly/daily and combine values of other corresponding rows每小时/每天重新采样时间戳并结合其他相应行的值
【发布时间】:2020-11-09 01:17:54
【问题描述】:

希望每小时/每天/每周/每月/每年重新采样时间范围并结合相应行中的值

数据框(26 列)

_id reqId statusCode requestUrl .... gatewayReqInTime ... payload
0    R1    401          /a             1560930471866      {"a":"b"}
1    R2    206          /b             1560935448236      {"c":"d"}
2    R3    200          /c             1560940623889      {"e":"f"}
3    R4    200          /d             1575365628749      {"g":"h"} 
4    R5    201          /e             1560935447889      {"i":"j"} 

需要的输出

gatewayReqInTime_Date count _id     reqId      statusCode   requestUrl ....... payload
2019-06-19 13:00:00    1    [0]      [R1]      [401]        ["/a"]                .
2019-06-19 14:00:00    2    [1,4]    [R2, R5]  [206, 201]   ["/b", "/e"]          .
2019-06-19 16:00:00    1    [2]      [R3]      [200]        ["/c"]                .
2019-12-03 15:00:00    1    [3]      [R4]      [200]        ["/d"]                .
 

我可以将时间戳转换为日期时间,重新采样并获取计数(输出的前 2 列)

但是,我在组合这些值时遇到了麻烦。尝试过groupby、agg等。

df['gateWayReqinTime_Date'] = df['gateWayReqinTime'].apply(lambda d: datetime.datetime.fromtimestamp(int(d)/1000).strftime('%Y-%m-%d %H:%M:%S'))
df2 = (df.groupby(pd.Grouper(key='gateWayReqinTime_Date', freq='H'))
        .size()
        .reset_index(name='Count'))
df2

PS : 这是 Javascript 开发人员在 Python 中的第一周。请提出将列标签视为动态或非特定的方法

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    以下方法接近您想要的:

    df = df.astype(str)
    df['gateWayReqInTime_Date'] = df['gateWayReqInTime'].apply(lambda d: datetime.datetime.fromtimestamp(int(d)/1000).strftime('%Y-%m-%d %H:%M:%S'))
    df.drop('gateWayReqInTime', inplace=True, axis=1)
    df['gateWayReqInTime_Date'] = pd.to_datetime(df['gateWayReqInTime_Date'])
    df2 = df.groupby(pd.Grouper(key='gateWayReqInTime_Date', freq='H')).agg(', '.join)
    df2['count'] = df.groupby(pd.Grouper(key='gateWayReqInTime_Date', freq='H'))['_id'].agg('count')
    
    print(df2.head())
    
                            _id   reqId statusCode requestUrl                 payload  count
    gateWayReqInTime_Date                                       
    2019-06-19 12:00:00       0      R1        401         /a               {'a': 'b'}      1
    2019-06-19 13:00:00    4, 1  R5, R2   201, 206     /e, /b   {'i': 'j'}, {'c': 'd'}      2
    2019-06-19 14:00:00                                                                     0
    2019-06-19 15:00:00       2      R3        200         /c               {'e': 'f'}      1
    2019-06-19 16:00:00                                                                     0
    

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 2018-08-26
      • 1970-01-01
      • 2013-04-29
      • 2020-07-10
      相关资源
      最近更新 更多