簡體   English   中英

如何找到年齡和計數列的人口 dataframe 的中位數?

[英]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 次,而是在執行逐元素乘法。

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM