Home > Enterprise >  How to populate a dataframe from row-by-row calculations?
How to populate a dataframe from row-by-row calculations?

Time:04-30

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.

CodePudding user response:

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....

Output DF

CodePudding user response:

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}))
  • Related