Home > Back-end >  Building a sum in a for loop from a dataset
Building a sum in a for loop from a dataset

Time:07-14

I have a dataset with two columns, Earning and Inflation_rate Assuming the Dataset looks like this

0   Earning   Inflation_rate
1   10000       0.00
2   12000       0.12
3   13000       0.13

I need to see how much it has built up over the course of these years, the formula is (Income build until last year x inflation rate) (first year earning/75)

For Year 1 that would be: ( 0 x 0.00 ) (10000/75)

For Year 2 that would be: (133 x 0.12) (12000/75)

My code is the following:

y=int(input("Please enter the number of years of contribution: "))
income_built=0
divide=75

for i in range(1,y 1):
    income_built=(income_built*df['Inflation_rate'].iloc[i-1,i]) (df['Earning'].iloc[i-1,i])/divide

print(int(income_built))

And I get the error IndexingError: Too many indexers

How can I solve this ? Thank you!

CodePudding user response:

The error is coming from your use of df['Inflation_rate'].iloc[i-1,i] and df['Earning'].iloc[i-1,i].

Pandas has a number of different ways of accessing values in a df, but the two most used are loc and iloc, both of which are explained well here.

I am slightly unclear about the formula you're trying to use. But I think if df['Inflation_rate'].iloc[i-1,i] is changed to df.loc[i-1,'Inflation_rate'] and df['Earning'].iloc[i-1,i] is changed to df.loc[i-1,'Earning', the error should dissappear.

  • Related