簡體   English   中英

計算 pandas dataframe 中每一列的第一個值的增長率並返回 Numpy 數組

[英]Calculate the growth ratio from first value in every column in a pandas dataframe and return a Numpy array

我的 function 需要一些幫助。

這就是我想要做的:

構建一個預測 model 可以讓我們最好地猜測給定年份的人口增長率可能是多少。 我們將計算人口增長率如下:

因此,我們只能計算 1961 年以后的增長率。

Write a function that takes the population_df and a country_code as input and computes the population growth rate for a given country starting from the year 1961. This function must return a return a 2-d numpy array that contains the year and corresponding growth rate for the國家。

Function 規格:

應該將 population_df 和 country_code 字符串作為輸入並返回 numpy 數組作為 output。 該數組應該只有兩列包含年份和人口增長率,換句話說,它應該有一個形狀(?,2)在哪里? 是數據的長度。

ℎ_ = __ - __ / __

應該將 population_df 和 country_code 字符串作為輸入並返回 numpy 數組作為 output。 該數組應該只有兩列包含年份和人口增長率,換句話說,它應該有一個形狀(?,2)在哪里? 是數據的長度。

輸入DF頭: 人口_df

我的代碼:(可更改)

def pop_growth_by_country_year(df,country_code):
    country_data = df.loc[country_code]
    for columnName, columnData in country_data.iteritems():
        country_data = ((country_data[columnData] - country_data[columnData-1]) / country_data[columnData-1])
    output = country_data.reset_index().to_numpy().reshape(-1, 2)
    return output

輸入功能(不可更改)

pop_growth_by_country_year(population_df,'ABW')

預期 output:

array([[ 1.961e+03,  2.263e-02],
       [ 1.962e+03,  1.420e-02],
       [ 1.963e+03,  8.360e-03],
       [ 1.964e+03,  5.940e-03],
            ...       ....
       [ 2.015e+03,  5.260e-03],
       [ 2.016e+03,  4.610e-03],
       [ 2.017e+03,  4.220e-03]])

我的輸入:

population_df = pd.DataFrame({
    '1960': {'ABW': 54211.0, 'AFG': 8996351.0, 'AGO': 5643182.0, 'ALB': 1608800.0, 'AND': 13411.0},
    '1961': {'ABW': 55438.0, 'AFG': 9166764.0, 'AGO': 5753024.0, 'ALB': 1659800.0, 'AND': 14375.0},
    '1962': {'ABW': 56225.0, 'AFG': 9345868.0, 'AGO': 5866061.0, 'ALB': 1711319.0, 'AND': 15370.0},
    '1963': {'ABW': 56695.0, 'AFG': 9533954.0, 'AGO': 5980417.0, 'ALB': 1762621.0, 'AND': 16412.0}
})
population_df

我的解決方案:

def pop_growth_by_country_year(df,country_code):
    current_population = df.loc[country_code]
    previous_population = current_population.shift(1)
    growth = (current_population-previous_population)/previous_population
    return growth.dropna().reset_index().astype(float).values

Output of pop_growth_by_country_year(population_df,'ABW')

array([[1.96100000e+03, 2.26337828e-02],
       [1.96200000e+03, 1.41960388e-02],
       [1.96300000e+03, 8.35927079e-03]])

請注意,由於您沒有第一年的先前人口(在這種情況下為 1960 年),您將錯過那一年的增長,因此len(output)=len(input)-1

暫無
暫無

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

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