s900n
s900n

Reputation: 3375

Pandas: Use selected amount of previous rows in apply function

lets say I have dataframe below:

index  value 
 1       1
 2       2
 3       3
 4       4

I want to apply a function to each row using previous two rows using "apply" statement. Lets say for example I want to multiple current row and previous 2 rows if it exists. (This could be any funtion)

Result:

index  value  result 
 1       1     nan 
 2       2     nan 
 3       3      6
 4       4      24

Thank you.

Upvotes: 1

Views: 109

Answers (3)

Scott Boston
Scott Boston

Reputation: 153460

You can try rolling with prod:

df['result'] = df['value'].rolling(3).apply(lambda x: x.prod())

Output:

   index  value  result
0      1      1     NaN
1      2      2     NaN
2      3      3     6.0
3      4      4    24.0

Upvotes: 1

wwnde
wwnde

Reputation: 26676

I presume you have more than four rows. If so, please try groupby every four rows, cumproduct, choose the last 2 and join to the original datframe.

df['value']=df.index.map(df.assign(result=df['value'].cumprod(0)).groupby(df.index//4).result.tail(2).to_dict())

If just four rows then this should you;

Lets try combine .cumprod() and .tail()

df['result']=df['value'].cumprod(0).tail(2)



 index  value  result
0      1      1     NaN
1      2      2     NaN
2      3      3     6.0
3      4      4    24.0

Upvotes: 0

Mehdi Golzadeh
Mehdi Golzadeh

Reputation: 2583

Use assign function:

df = df.assign(result = lambda x: x['value'].cumprod().tail(len(df)-2))

Upvotes: 1

Related Questions