[Python] calculate diff to previous matching row in a dataframe

Discussão em 'Python' iniciado por Stack, Julho 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a series of timestamps (+ other data) that come from 2 separate streams of data ticking at different rates, an example below (NB: the frequency of the real data has some jitter so it's not a simple fixed stride like below)

    src,idx,ts
    B,1,20
    A,1,100
    A,2,200
    A,3,300
    B,2,320
    A,4,400
    A,5,500
    A,6,600
    B,3,620


    for each A tick, I need to calculate the offset from the preceding B tick so it would become

    src,idx,ts
    A,1,80
    A,2,180
    A,3,280
    A,4,80
    A,5,180
    A,6,280


    how to do this in pandas without iteration?

    I thought of some sort of rolling window but with a dynamic/criteria based window or some hybrid of merge_asof and group by but can't think of a way to do it.

    Continue reading...

Compartilhe esta Página