Reputation: 963
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
Upvotes: 0
Views: 967
Reputation: 1718
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())
Upvotes: 1