1

I have a function that use b(t-1) variable like:

def test_b(a,b_1):
     return a + b_1

Assume the following dataframe:

df = pd.DataFrame({'a':[1,2,3],'b':np.nan})

I am assigning the b_1 initial value:

df['b'].ix[0]=0

and then (using my Matlab experience), i use the loop:

for i in range(1,len(df)):
    df['b'].ix[i] = test_b(df['a'].ix[i],df['b'].ix[i-1])

output:

  a|b
0|1|0
1|2|2
2|3|5

Is it a more elegant way to do the same?

1 Answers1

1

You never want to do assignments like this, as this is chained indexing

This is a recurrent relation, so not easy way ATM to do this in a super performant manner, though see here.

here is an open issue about this with a pointer to this which uses ifilter to solve the relation.

Community
  • 1
  • 1
Jeff
  • 125,376
  • 21
  • 220
  • 187