代码之家  ›  专栏  ›  技术社区  ›  retorquere

计算中连续值组的最大运行长度

  •  0
  • retorquere  · 技术社区  · 8 年前

    给定这样一个数据集:

    values = ([ 'motorway' ] * 5) + ([ 'link' ] * 3) + ([ 'motorway' ] * 7)
    
    df = pd.DataFrame.from_dict({
      'timestamp': pd.date_range(start='2018-1-1', end='2018-1-2', freq='s').tolist()[:len(values)],
      'road_type': values,
    })
    df.set_index('timestamp')
    df['delta_t'] = (df['timestamp'] - df['timestamp'].shift()).fillna(0)
    

    我想知道 delta_t 每组连续道路类型;鉴于此 三角洲 将会是 1s 在这个例子中,我想找出 motorway 7s 和 link 3s . 在实践中,会有更多的道路类型 三角洲

    编辑:提供的解决方案 here 似乎相似,但它不求和的时间,也没有选择最大的每一组。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Peter Leimbigler    8 年前

    创建一个新列,用唯一整数标记相同道路类型的每个“梯段”,然后按该列分组并求和:

    df['run'] = (df['road_type'] != df['road_type'].shift()).astype(int).cumsum()
    
    df
                 timestamp road_type  delta_t  run
    0  2018-01-01 00:00:00  motorway 00:00:00    1
    1  2018-01-01 00:00:01  motorway 00:00:01    1
    2  2018-01-01 00:00:02  motorway 00:00:01    1
    3  2018-01-01 00:00:03  motorway 00:00:01    1
    4  2018-01-01 00:00:04  motorway 00:00:01    1
    5  2018-01-01 00:00:05      link 00:00:01    2
    6  2018-01-01 00:00:06      link 00:00:01    2
    7  2018-01-01 00:00:07      link 00:00:01    2
    8  2018-01-01 00:00:08  motorway 00:00:01    3
    9  2018-01-01 00:00:09  motorway 00:00:01    3
    10 2018-01-01 00:00:10  motorway 00:00:01    3
    11 2018-01-01 00:00:11  motorway 00:00:01    3
    12 2018-01-01 00:00:12  motorway 00:00:01    3
    13 2018-01-01 00:00:13  motorway 00:00:01    3
    14 2018-01-01 00:00:14  motorway 00:00:01    3
    
    
    df.groupby('run').agg({'road_type': 'first', 'delta_t': 'sum'}).reset_index(drop=True).groupby('road_type').max()
    
               delta_t
    road_type         
    link      00:00:03
    motorway  00:00:07