我对 Python 很陌生,但正在尝试对一些公司流程进行一些基本的自动化。
其中一个过程是基本预测,将数值平均增长添加到上个月的交易量中以获得下个月的预测。 然后迭代以获得更长期的观点。
我已经创建了:
这基本上就是我想要创建的过程:
计算: latest_row['month'] + 1(获取下个月的数字) latest_row['volume'] + numeric_avg_growth
将上述计算作为一行附加到主数据帧(因此这将成为latest_row变量)
然后再次重复该过程
这意味着您不断添加到数据框并根据最近添加的内容进行计算。
我不知道如何运行一次循环,附加该结果,然后根据新附加的数字再次运行循环。
我确信这相当简单,但我无法弄清楚。任何帮助将非常感激!!
数据和代码示例:
#Creating dataframe
data = [[2022, 1, 512116, NaN], [2022, 2, 524775, -1.73],
[2022,3, 600017, 19.88]]
df = pd.DataFrame(data, columns=['year', 'month', 'volume',
'volume_growth'])
#Creating average volume growth percentage variable
avg_vol_growth = df['volume_growth'].mean()
#Creating average volume growth as integer variable
avg_vol_growth_int = np.sum(avg_vol_growth/100)
#Variable that shows just the last row in the dataframe
latest_row = df.tail(1)
#Creating numerical average growth variable (vol)
#Calculated using (latest actual volume * average growth integer)/12
numerical_avg_growth = np.sum(((latest_row['volume'])*avg_vol_growth_int)/12)
例如,我需要的结果是将第 4,5 和 6 个月的交易量添加到数据框中。 通过将 numeric_avg_growth 添加到上个月的交易量来计算。
例如 年月量 2022年1月512116 2022.2.524775 2022年3月600017 2022 年 4 月(600017 + numeric_avg_growth) 2022 年 5 月(第 4 个月成交量 + numeric_avg_growth) 2022 年 6 月(第 5 个月成交量 + numeric_avg_growth)
在创建数据帧之前考虑计算体积和 avg_growth 以获得更好的效率和性能。查看这篇有用的帖子:链接
import numpy as np
data = {
"year": [2022]*6,
"month": [range(1, 7)],
"volume": [512116, 524775, 600017],
"volume_growth": [0, -1.73, 19.88]
}
for i in range(4, 7):
avg_growth = np.mean(data["volume_growth"][1:])
data["volume"].append(data["volume"][-1] + avg_growth)
data["volume_growth"].append(data["volume"][-1] - data["volume"][-2])