简体   繁体   English

从 Pandas 的前一行中查找值

[英]Finding a value from the previous row in Pandas

I have the following dataframe我有以下数据框

Date             UUID         Value         RANK
01/03/2019        A            0              2
28/02/2019        A            1              1
28/02/2019        B            2              2 
26/02/2019        B            3              1
24/02/2019        C            4              2
21/02/2019        C            1              1

And I want to get the following:我想得到以下内容:

Date             UUID         Value         RANK     PreValue
01/03/2019        A            0              2       1
28/02/2019        A            1              1       N/A
28/02/2019        B            2              2       3
26/02/2019        B            3              1       N/A
24/02/2019        C            4              2       1
21/02/2019        C            1              1       N/A

How would I go about getting the previous value?我将如何获得以前的价值?

Any Help would be greatly appreciated.任何帮助将不胜感激。

EDIT: So effectively what I want to do is shift the value based on the rank and uuid编辑:所以我想要做的是有效地根据等级和 uuid 移动值

You were almost there, just missing the .groupby :.groupby ,只是错过了.groupby

df['PrevValue'] = df.sort_values(['UUID', 'RANK']).groupby('UUID').Value.shift(1)

print(df)
         Date UUID  Value  RANK  PrevValue
0  01/03/2019    A      0     2        1.0
1  28/02/2019    A      1     1        NaN
2  28/02/2019    B      2     2        3.0
3  26/02/2019    B      3     1        NaN
4  24/02/2019    C      4     2        1.0
5  21/02/2019    C      1     1        NaN

A fun way , using idxmax with drop , the just shift whole Value and condition assign一种有趣的方式,使用带有drop idxmax ,只需shift整个值和条件分配

df.loc[df.index.drop(df.groupby('UUID').RANK.idxmin()),'New']=df.Value.shift(-1)
df
         Date UUID  Value  RANK  New
0  01/03/2019    A      0     2  1.0
1  28/02/2019    A      1     1  NaN
2  28/02/2019    B      2     2  3.0
3  26/02/2019    B      3     1  NaN
4  24/02/2019    C      4     2  1.0
5  21/02/2019    C      1     1  NaN

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

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