简体   繁体   中英

Sort Pandas Dataframe based on previous row value

I have a dataframe that looks like:

Name      Previous Name
Alice     NaN
Charlie   Bob
Bob       Alice
Fred      Eddy
Danny     Charlie
Eddy      Dan

I would like to sort the dataframe so that is looks like:

Name      Previous Name
Alice     NaN
Bob      Alice
Charlie  Bob
Danny    Charlie
Eddy     Danny
Fred     Eddy

I know the boolean test involves something like

dataframe['Value'] = dataframe['PreviousValue'].shift(1)

But how can I use that as a sort criteria?

EDIT: Changed example from letters to names

Sort of values, then shift:

df = df.sort_values('Value')
df['Previous Value'] = df['Value'].shift()

Output:

  Value Previous Value
0     A            NaN
2     B              A
1     C              B
4     D              C
5     E              D
3     F              E

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