简体   繁体   English

根据前一行值对 Pandas Dataframe 进行排序

[英]Sort Pandas Dataframe based on previous row value

I have a dataframe that looks like:我有一个 dataframe 看起来像:

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:我想对 dataframe 进行排序,如下所示:

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

I know the boolean test involves something like我知道 boolean 测试涉及类似

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: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据每行上一行中的值更新pandas dataframe当前行属性 - Update pandas dataframe current row attribute based on its value in the previous row for each row Python Pandas Dataframe 根据同一列中的前一行值计算新行值 - Python Pandas Dataframe calculating new row value based on previous row value within same column 如何根据 pandas DataFrame 中的条件从当前行值中减去前一行值? - how to subtract previous row value from current row value based on condition in pandas DataFrame? 如何根据行对 pandas dataframe 进行排序? - How to sort pandas dataframe based on row? 将值与 Pandas DataFrame 中的前一行进行比较 - Comparing value with previous row in Pandas DataFrame 从上一行访问值 pandas dataframe - Access value from previous row pandas dataframe pandas - 访问 Dataframe 中前一行的值 - pandas - Access value in a previous row in a Dataframe 如何根据 Pandas dataframe 中上一行的行值创建新列? - How to create a new column based on row value in previous row in Pandas dataframe? 根据上一行中的值来操作熊猫数据帧单元的值而无需迭代 - manipulating value of pandas dataframe cell based on value in previous row without iteration Pandas Dataframe基于前一行,将值添加到新列,但该列的最大值限于该列 - Pandas Dataframe Add a value to a new Column based on the previous row limited to the maximum value in that column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM