分层随机抽样

使用 Python 分析调查数据

EbunOluwa Andrew

Data Scientist

什么是分层随机抽样

  • 分层抽样更能反映总体
  • 将总体按相似属性划分为离散单元(层)
  • 重新抽样,使样本比例匹配总体

人口多样性变化:大型群体构成变化

使用 Python 分析调查数据

为何使用分层随机抽样?

  • 最小化选择偏差
  • 提高特定群体的代表性
  • 示例:
    • 估计不同人群的收入
    • 选举民调估计
    • 预估预期寿命

手持计数器统计人数

使用 Python 分析调查数据

何时不应使用分层随机抽样

  • 子组不应重叠
    • 受试者落入多个组会导致失真
  • 调查问题中的重叠示例
    • 您在现岗位工作了多久?
      • 1-2 年
      • 2-4 年

思考的女士

使用 Python 分析调查数据

ABC 公司现场办公调查结果

| employee_id | gender | onsite_work |
|-------------|--------|-------------|
|    fffe6838 | Male   | Yes         |
|   fffe12184 | Female | Yes         |
|    fffe9404 | Female | Yes         |
|   fffe17578 | Male   | Yes         |
|   fffe22257 | Female | Yes         |
|    fffe6217 | Male   | Yes         |
|    fffe7828 | Female | Yes         |
|   fffe18192 | Male   | Yes         |
|    fffe2839 | Female | Yes         |
|   fffe16173 | Female | Yes         |

使用 Python 分析调查数据

检查总体比例

survey.gender.value_counts(normalize=True)
Female    0.556
Male      0.444
Name: gender, dtype: float64
使用 Python 分析调查数据

绘制总体比例

import pandas as pd
import matplotlib.pyplot as plt

survey.gender.value_counts().plot.pie()

调查中女性与男性比例

使用 Python 分析调查数据

分层抽样示例

strat_sample = 
survey.groupby(
  'gender', group_keys = False).apply(
  lambda x: x.sample(frac = 0.1))
| employee_id | gender | onsite_work |
|-------------|--------|-------------|
|    fffe4934 | Female | Yes         |
|    fffe3958 | Female | Yes         |
|      fffe18 | Female | Yes         |
|     fffe283 | Female | Yes         |
|   fffe20382 | Female | Yes         |
|    fffe8721 | Male   | Yes         |
|    fffe5955 | Male   | Yes         |
|    fffe7081 | Male   | Yes         |
|     fffe353 | Male   | Yes         |
|    fffe1765 | Male   | Yes         |

使用 Python 分析调查数据

检查样本比例

原始总体

survey.gender.value_counts(normalize=True)

分层样本

strat_sample.gender.value_counts(
  normalize=True))
Female    0.556
Male      0.444
Name: gender, dtype: float64
Female    0.56
Male      0.44
Name: gender, dtype: float64
使用 Python 分析调查数据

让我们练习!

使用 Python 分析调查数据

Preparing Video For Download...