How to populate a dataframe from row-by-row calculations?

I am seeking to populate a pandas dataframe row-by-row, whereby each new row is calculated on the basis of the contents of the previous row. I am using this for simple financial projections.

Let us take a dataframe ‘df_basic_financials’:

df_basic_financials = pd.DataFrame({'current_account': [18357.], 'savings_account': [14809.]})

Now I want to forecast what my current and saving accounts will look like in five years, assuming that I earn 24000 a year and that my saving accounts yields 2% yearly, assuming I spend zero money and do not transfer any money to my savings account.

How do I write the code so that I get this:

       current_account    savings_account   
0      18357              14809       
1      42357              15105.18
2      66357              15407.2836

etc… for any number of years I want, each time using the calculation ‘value of the previous row in the same column + 24000’ for current_account and ‘value of the previous row in the same column*1.02’ for savings_account.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can get the input from user on number of years and then run the code this way

import pandas as pd
df = pd.DataFrame({'current_account': [18357], 'savings_account':[14809]})

years = int(input("Enter years: "))
for n in range(years):
    lastrow = df.iloc[len(df)-1]
    print(lastrow[0], lastrow[1])
    df.loc[len(df.index)] = [int(lastrow[0]) +24000, int(lastrow[1])*1.02]
df

Out will be….

How to populate a dataframe from row-by-row calculations?

Method 2

Just use math

df_basic_financials = pd.DataFrame({'current_account': [18357.], 'savings_account': [14809.]})

current_account_projection = [df_basic_financials['current_account'].iloc[-1] + (24000 * i) for i in range(10)]
savings_account_projection = [df_basic_financials['savings_account'].iloc[-1] * (1.02 ** i) for i in range(10)]

df_basic_financials = pd.DataFrame({'current_account': current_account_projection, 'savings_account': savings_account_projection})

if you really want an interative solution, apply the function on savings_account.iloc[-1]

current_account_next = df_basic_financials.iloc[-1]['current_account'] + 24000
savings_account_next = df_basic_financials.iloc[-1]['savings_account'] * 1.02
df_basic_financials = df_basic_financials.append(pd.Series({'current_account': current_account_next, 'savings_account': savings_account_next}))


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x