2

I want to iterate through df and calculate the column a values which needs column b and c values. The formula is like this:

    for i in range(1, len(df)):
     df.a[i] = df.b[i-1]*(2**df.c[i])
     df.b[i] = df.a[i]*0.5 + 1

I want to have faster calculations maybe using apply func or lambda func, but I don't know when I define apply function in python, how can I access previous row's value?

Example input (df.a[0] df.b[0] df.c) and expected output df.a: df

a   b   c
0   1   1
4   3   2
24  13  3
208 105 4
2
  • 1
    please provide a sample input data 5-7 rows and expected output Commented Mar 14, 2016 at 17:51
  • I added the input and expected output, also updated the calculation I want. Sorry for the confusion. Thanks! Commented Mar 14, 2016 at 18:06

1 Answer 1

1

you need shift() function:

In [9]: df = pd.DataFrame({'b': [1,3,13,105], 'c': [1,2,3,4]})

In [10]: df
Out[10]:
     b  c
0    1  1
1    3  2
2   13  3
3  105  4

In [11]: df['a'] = (df.b.shift()*(2**df.c)).fillna(0)

In [12]: df
Out[12]:
     b  c    a
0    1  1    0
1    3  2    4
2   13  3   24
3  105  4  208

In [13]: df.b = df.a*0.5+1

In [14]: df
Out[14]:
     b  c    a
0    1  1    0
1    3  2    4
2   13  3   24
3  105  4  208

In [15]: df[['a','b','c']]
Out[15]:
     a    b  c
0    0    1  1
1    4    3  2
2   24   13  3
3  208  105  4
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for reply, sorry I didn't put my whole function in the previous post. I updated the function, the column b value actually needs current row a column's value for calculation.
@user5025141, what is the source dataframe - i mean b column
@user5025141, i've updated my answer. please check it
Sorry, there is no source data for column b. I only know df.b[0], the b column is calculated step by step.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.