简体   繁体   中英

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 ie 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

尝试:

df['From to'] = df['last status'] + '->' + df['status']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM