【问题标题】:creating a function for mathematical data imputation python为数学数据插补python创建一个函数
【发布时间】:2020-08-01 18:51:36
【问题描述】:

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

  • 公式是 2 * 2001 年的值 - 2002 年的值

我目前在 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

【问题讨论】:

  • 您也可以打印原始数据框(或相关的行和列)吗?您当前的代码替换了 geo_full 是克罗地亚的整个列。
  • @DjerroNeth 原始数据框非常大,包括 2000-2019 年的大约 30 个国家; 0 数据的问题仅适用于 2000 年的克罗地亚
  • 您好,您尝试我的回答了吗?
  • @RichieV 是的,但最终没有使用它,因为我放弃了一些其他系列,丢失了大量数据。决定一个一个来做

标签: python function dataframe replace missing-data


【解决方案1】:

因此,您正在尝试用您的公式填充 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)

【讨论】:

  • 谢谢@RichieV - 数据集中包含 30 个国家,但问题仅在于克罗地亚,没有其他 0 值。我已经将索引设置为 geo_full 但我想我可以重新设置它。我遵循了您建议的代码,但在 df.iloc[0] = df.iloc[1]*2 - df.iloc[1] TypeError: unsupported operand type(s) for -: 'str' and 'str' 上收到错误
  • 工作得很好,有一点小变化: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) 我现在如何调用该函数,但对于我所拥有的特定情况,即填充指标 fertile_age_pct 等的值?
  • 缺少什么? fixed_data 不是预期的结果吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 2019-03-14
  • 1970-01-01
相关资源
最近更新 更多