首页 > 解决方案 > 为数学数据插补python创建一个函数

问题描述

我正在执行许多类似的操作,我想编写一个函数,但我什至不知道如何处理这个问题。我正在计算以下系列的 0 数据的值:

我目前在Python中一一做:

print(full_data.loc['Croatia', 'fertile_age_pct'])
print(full_data.loc['Croatia', 'working_age_pct'])
print(full_data.loc['Croatia', 'young_age'])
print(full_data.loc['Croatia', 'old_age'])

full_data.replace(to_replace={'fertile_age_pct': {0:(2*46.420061-46.326103)}}, inplace=True)
full_data.replace(to_replace={'working_age_pct': {0:(2*67.038157-66.889212)}}, inplace=True)
full_data.replace(to_replace={'young_age': {0:(2*0.723475-0.715874)}}, inplace=True)
full_data.replace(to_replace={'old_age': {0:(2*0.692245-0.709597)}}, inplace=True)

数据框(full_data):

geo_full  year   fertile_age_pct    working_age_pct    young_age    old_age
Croatia   2000   0                  0                  0            0
Croatia   2001   46.420061          67.038157          0.723475     0.692245
Croatia   2002   46.326103          66.889212          0.715874     0.709597
Croatia   2003   46.111822          66.771187          0.706091     0.72444
Croatia   2004   45.929829          66.782133          0.694854     0.735333
Croatia   2005   45.695932          66.742514          0.686534     0.747083

标签: pythonfunctiondataframereplacemissing-data

解决方案


所以你试图用你的公式填充 2000 年的 0 值。如果您在 DataFrame 中有任何其他国家/地区,那么它可能会变得混乱。

假设带 0 的年份始终是每个国家/地区的第一年,试试这个:

full_data.set_index('year', inplace=True)
fixed_data = {}
for country, df in full_data.groupby('geo_full')[full_data.columns[1:]]:
    if df.iloc[0].sum() == 0:
        df.iloc[0] = df.iloc[1] * 2 - df.iloc[0]
    fixed_data[country] = df
fixed_data = pd.concat(list(fixed_data.values()), keys=fixed_data.keys(), names=['geo_full'], axis=0)

推荐阅读