如何在 Python 中计算分类变量的加权平均值?

问题描述 投票:0回答:1

我正在尝试计算印度 0-5 岁儿童的发育迟缓情况。我已经从国土安全部儿童网站加载了数据集。我的 Y 变量列为: a> hw70(0=未发育迟缓,1=发育迟缓)

属性列:

  • a> sex_children(男= 1, 女= 0)
  • b> DHS 自己给出的样本(0.26 百万家庭)的权重列(wt= v005/1000000)

在 stata 中,将 hw70 和 sex_children(iweight= wt) 制表更容易,这消除了结果中存在的任何类型的权重偏差。

在 python 中,我使用交叉表来查找输出。但是如何将给定的样本权重应用于像 sex_children 这样的分类列的样本数据集?

状态:

tab hw70 sex_children[iweight=wt], row

nt_ch_stun |     sex_children
      hw70 |      male     female |     Total
-----------+----------------------+----------
         0 | 66,638.05  63,547.39 | 130,185.4 
           |     51.19      48.81 |    100.00 
-----------+----------------------+----------
         1 | 37,892.08  33,674.05 | 71,566.13 
           |     52.95      47.05 |    100.00 
-----------+----------------------+----------
     Total | 104,530.1  97,221.45 | 201,751.6 
           |     51.81      48.19 |    100.00 

如何在 Python 中做同样的事情,尤其是 iweight 部分?我正在使用交叉表,但获得的信息非常有限且存在权重偏差。请帮忙。谢谢。

python pandas stata numpy-ndarray statsmodels
1个回答
0
投票

没有数据样本会让人不确定,但这里是如何做到这一点的:

import pandas as pd

# load sample dataset into a pandas dataframe
df = pd.DataFrame({
    'sex': [1, 0, 1, 0, 1, 1, 0, 1, 0, 1],
    'age': [3, 2, 4, 1, 5, 2, 1, 4, 5, 3],
    'height': [80, 70, 85, 65, 90, 80, 70, 95, 75, 85],
    'weight': [10, 8, 12, 7, 14, 10, 8, 16, 9, 12],
    'stunting': [1, 0, 1, 0, 1, 1, 0, 1, 0, 1]
})

print(df)

wts = df['weight'] / 1000000

xtab = pd.crosstab(df['stunting'], df['sex'], values=wts, aggfunc=sum, normalize='index')

xtab = xtab.applymap(lambda x: '{:,.2f}'.format(x))
xtab.columns.name = 'sex'
xtab.index.name = 'stunting'
xtab.loc['Total'] = xtab.sum(numeric_only=True, axis=0)
xtab = xtab.append(xtab.sum(numeric_only=True, axis=1).rename('Total'))
xtab.iloc[:,[1,0,2]]

这将返回这样的东西

             1     0  Total
stunting                   
0         0.00  1.00    NaN
1         1.00  0.00    NaN
Total      NaN   NaN    NaN
Total      0.0   0.0    0.0
© www.soinside.com 2019 - 2024. All rights reserved.