我正在尋求逐行填充熊貓資料框,其中每一新行都是根據前一行的內容計算的。我將其用于簡單的財務預測。
讓我們取一個資料框“df_basic_financials”:
df_basic_financials = pd.DataFrame({'current_account': [18357.], 'savings_account': [14809.]})
現在我想預測五年后我的活期賬戶和儲蓄賬戶會是什么樣子.
我如何撰寫代碼以便得到這個:
current_account savings_account
0 18357 14809
1 42357 15105.18
2 66357 15407.2836
等等...對于我想要的任何年數,每次使用計算“同一列中上一行的值 24000”作為 current_account 和“同一列中前一行的值 *1.02”作為 Saving_account。
uj5u.com熱心網友回復:
您可以從用戶那里獲取有關年數的輸入,然后以這種方式運行代碼
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
出來會....

uj5u.com熱心網友回復:
只用數學
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})
如果您真的想要一個互動式解決方案,請將該功能應用于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}))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468416.html
標籤:Python python-3.x 熊猫 数据框
