Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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}))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading