如何找到具有年龄和计数列的人口数据框的中位数?

How to find the median for dataframe of population with columns of age and count?

df 看起来像这样:

   age  population
0   20           2
1   21           3
2   22           2
3   23           5
4   24           7

df = pd.DataFrame({ 'age': [20, 21, 22, 23, 24], 'population': [2, 3, 2, 5, 7]})

我想计算总人口的中位年龄。有没有简单的方法可以做到这一点?

得到这样的平均值,但我需要中位数:

df['years'] = df['age'] * df['population']
average_age= (df['years'].sum()/df['population'].sum())

将两个 pandas 系列相乘不同于将列表相乘 - 您不是将每个值复制 N 次,而是执行 element-wise 乘法。

使用pd.Series.repeat将每个元素重复N次,然后使用.median方法计算得到的pandas系列的中位数:

df = pd.DataFrame({ 'age': [20, 21, 22, 23, 24], 'population': [2, 3, 2, 5, 7]})
m = df['age'].repeat(df['population']).median()
print(m)  # output: 23.0