1

I want to loop through a data frame and then fill a column of the frame with interest rates from a complex calculation. Apparently, the best way to loop through a frame is to use iterrows - But when I use iterrows, I get integer values only:

import pandas
df = pandas.DataFrame({"A": [1,2,3,4,5]})
df['B']=0
for index, row in df.iterrows():
    row['B']=row['A']*10.05
df

returns

   A   B
0  1  10
1  2  20
2  3  30
3  4  40
4  5  50

Which is incorrect, given that all values in A were multiplied by 10.05.

The example below, gives the correct results:

df['B']=df['A']*10.05

   A      B
0  1  10.05
1  2  20.10
2  3  30.15
3  4  40.20
4  5  50.25

As said, it is not easy to use this method, because the calculations are complex.

Can I use iterrows to produce the correct result?

Martien Lubberink
  • 2,614
  • 1
  • 19
  • 31

1 Answers1

1

It seems you need assign scalar values with loc (at, ix):

for index, row in df.iterrows():
    df.loc[index, 'B'] =row['A']*10.05
print (df)
   A      B
0  1  10.05
1  2  20.10
2  3  30.15
3  4  40.20
4  5  50.25

But better is use apply with custom function:

df = pandas.DataFrame({"A": [1,2,3,4,5]})


def f(x):
    x['B'] = x.A * 10.05
    #another code
    return x

df = df.apply(f, axis=1)
print (df)
     A      B
0  1.0  10.05
1  2.0  20.10
2  3.0  30.15
3  4.0  40.20
4  5.0  50.25
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks, the loop works! I will add a follow up that looks into the apply function, see if that can be solved too. – Martien Lubberink Mar 04 '17 at 20:23
  • See here my follow up, in this [link](http://stackoverflow.com/questions/42601765/how-to-efficiently-fill-a-column-of-dataframe-with-values-calculated-from-other). – Martien Lubberink Mar 04 '17 at 21:46
  • Thank you, but I am going to bed now. But one advice - add tag pandas to your new question. good luck! – jezrael Mar 04 '17 at 21:57