如何计算加权平均值

时间:2020-02-07 22:31:47

标签: python pandas

Country  life_expectancy   population 

Germany     70               3000000
France      75               450000
USA         70               350000
India       65               4000000
Pakistan    60               560000
Belgium     68               230000

我想根据以下公式计算加权平均预期寿命:

∑ (????? × ????)/ ∑ ????  

where ????? = life expectancy
      ???? = population

注意:加权平均预期寿命是将预期寿命乘以每个国家的总人口除以每个国家的总人口之和而得出的

有人可以告诉我如何使用for循环解决此问题吗?

3 个答案:

答案 0 :(得分:1)

使用numpy.average(..., weights=...)

参考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html

import numpy as np

res=np.average(df["life_expectancy"], weights=df["population"])

输出:

67.22817229336438

答案 1 :(得分:0)

带有for循环

numerator, denominator = 0, 0
for i in df.index:
    numerator += df.loc[i, 'life_expectancy'] * df.loc[i, 'population']
    denominator += df.loc[i, 'population']
weighted_average = numerator / denominator

或使用熊猫以任何更易于阅读的方式更快地完成所有操作(这是我推荐的解决方案)

weighted_average = (df['life_expectancy']*df['population']).sum() / df['population'].sum()

答案 2 :(得分:0)

实际上不需要for循环,您可以直接计算

Game.find().then(games => {
        console.log(req.body)
        const items = games;
        const page = parseInt(req.body.pageIndex) || 1;
        const pageSize = parseInt(req.body.pageSize) || 10;
        const pager = paginate(items.length, page, pageSize);
        console.log(pager.endIndex)
        const pagedGames = items.slice(pager.startIndex, pager.endIndex + 1);

        pagedGames.forEach(game => {
          const matchTime = moment.utc(game.matchTime, 'YYYY-MM-DD HH:mm')
          const localTime = matchTime.local().format('LLL');
          game.matchTime = localTime;
        })
        
        return res.status(200).json({
          message: 'Games fetched successfully',
          pager,
          games: pagedGames,
          numberOfGames: items.length
        });