我有一个数据框长这个样子:
Out[14]:
impwealth indweight
16 180000 34.200
21 384000 37.800
26 342000 39.715
30 1154000 44.375
31 421300 44.375
32 1210000 45.295
33 1062500 45.295
34 1878000 46.653
35 876000 46.653
36 925000 53.476
我想要使用列impwealth
中的频率权重来计算加权中位数,我的伪代码如下:
# Sort `impwealth` in ascending order
df.sort('impwealth', 'inplace'=True)
# Find the 50th percentile weight, P
P = df['indweight'].sum() * (.5)
# Search for the first occurrence of `impweight` that is greater than P
i = df.loc[df['indweight'] > P, 'indweight'].last_valid_index()
# The value of `impwealth` associated with this index will be the weighted median
w_median = df.ix[i, 'impwealth']
这种方法看起来有些笨重,而且我不确定它是否正确。在pandas参考资料中,我没有找到内置的方法来执行此操作。如何寻找加权中位数的最佳方法?
df['indweight'].sum() * (.5)
将会得到一个约为219
的值,而你的indweight
值中没有一个超过该值。调用df['indweight'].median()
将得到44.835,而使用mean()
则会得到43.783。 - EdChumdf['indweight'].sum() * (.5)
应该计算数据中落在第50个百分位以下的观测值数量,因为indweight
是频率权重。因此,indweight
的均值和中位数超过其总和是有道理的。 - svenkateshindweight
的.cumsum()
而不是indweight
本身。也许可以看一下我下面的答案。 - prooffreader