pythonpandasgroup-byappendrow-value-expression

append value of next row with current row pandas groupby id


I have a dataframe as

id status
1  owner
1  retail
1  shop
1  customer
2  owner
2  retail

I created new column of Last status like

id status   Last status
1  owner     NA
1  retail    owner
1  shop      retail
1  customer  shop
2  owner     NA
2  retail    owner

But I want to create a column of the flow i.e append last status with the next value like

id status   From To
1  owner     NA
1  retail    owner -> retail
1  shop      retail -> shop
1  customer  shop -> customer
2  owner     NA
2  retail    owner -> retail

Big Thanks in advance


Solution

  • Let's do groupby + shift and concatenate with status column:

    df['From to'] = df.groupby('id')['status'].shift() + ' -> ' + df['status']
    

       id    status           From to
    0   1     owner               NaN
    1   1    retail   owner -> retail
    2   1      shop    retail -> shop
    3   1  customer  shop -> customer
    4   2     owner               NaN
    5   2    retail   owner -> retail