简体   繁体   中英

Pandas - calculate row value based on previous calculated row value

What is the most effective way to solve following problem with pandas?:

Let's asume we have following df:

        v1    v2   
index
0       1     2     
1       5     6    
2       7     3     
3       9     4       
4       5     1     

Now we want to calculate a third value (v3) based on following function:

if df.v1.shift(1) > df.v3.shift(1):
    df.v3 = max(df.v2, df.v3.shift(1))
else:
    df.v3 = df.v2

The desired output should look like:

        v1    v2    v3
index
0       1     2     2
1       5     6     6
2       7     3     3
3       9     4     4    
4       5     1     4

THX & BR from Vienna

I believe the following two lines gets to your result:

df['v3'] = df['v2']
df['v3'] = df['v3'].where(df['v1'].shift(1)<=df['v3'].shift(1),pd.DataFrame([df['v2'],df['v3'].shift(1)]).max())

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