Python Pandas using previous value in Dataframe

I have a function using the variable b (t-1):

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

Suppose the following frame:

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

I assign the initial value b_1:

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

and then (using my Matlab experience), I use a loop:

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

conclusion:

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

Is this a more elegant way to do the same?

+1
source share
1 answer

You will never want to make assignments like this, since this is chain indexing.

This is a recursive relationship, so it’s not an easy ATM tool to do it in a super-executive way, but see here .

, ifilter .

+1

Source: https://habr.com/ru/post/1673043/


All Articles