簡體   English   中英

Pandas - 使用范圍(x)在“for”循環中填充 dataframe

[英]Pandas - populate dataframe in 'for' loop with range(x)

我有一個 function 構建一個空的 dataframe,如下所示:

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

我該怎么做呢?

您可以創建助手列表:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM