【问题标题】:How to find the median for dataframe of population with columns of age and count?如何找到具有年龄和计数列的人口数据框的中位数?
【发布时间】:2020-08-05 12:24:28
【问题描述】:

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())

【问题讨论】:

    标签: python pandas median


    【解决方案1】:

    将两个 pandas Series 相乘不同于将列表相乘 - 您不是将每个值复制 N 次,而是在执行逐元素相乘。

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

    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
    

    【讨论】:

    • 完美。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多