首页 > 解决方案 > Pandas - 使用 range(x) 在“for”循环中填充数据框

问题描述

我有一个构建空数据框的函数,如下所示:

def malthusian_growth():
   # formula
   def growth1(r, x):
       y = r*(1-x)
       return y

    todays_date = datetime.datetime.now().date()
    index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
    columns = ["year", "population"]
    df  = pd.DataFrame(index=index, columns=columns)

现在我想用以下循环填充它:

    population = 0.02
    for item in range(10):
        next_population = growth1(r=2.7, x=population)
        population+=next_population

我该怎么做呢?

标签: pythonpandas

解决方案


您可以创建助手列表:

def growth1(r, x):
       y = r*(1-x)
       return y

out = []
population = 0.02
for item in range(10):
    next_population = growth1(r=2.7, x=population)
    population+=next_population

    out.append(population)

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
columns = ["year", "population"]
df  = pd.DataFrame({'population':out}, index=index)
print (df)
            population
2020-04-10    2.666000
2020-04-11   -1.832200
2020-04-12    5.814740
2020-04-13   -7.185058
2020-04-14   14.914599
2020-04-15  -22.654818
2020-04-16   41.213190
2020-04-17  -67.362423
2020-04-18  117.216119
2020-04-19 -196.567402

推荐阅读