估计差异的显著性
带误差条的折线图可以大致反映趋势,但逐年差异是否具有统计显著性呢?在本练习中,您将判断费城中位房价在不同年份之间的变化是否显著。您将评估 2011 年到 2017 年之间各年的差异。
两样本 Z 统计量的公式为:
$$Z = \frac{x_1 - x_2}{\sqrt{SE_{x_1}^2 + SE_{x_2}^2}}$$
已提供一个 DataFrame philly,其包含 median_home_value、median_home_value_moe 和 year 列。
已将 pandas 以 pd 导入,并从 numpy 模块中导入了 sqrt 函数。
本练习是课程的一部分
使用 Python 分析美国人口普查数据
练习说明
- 将
x1设为当年的中位房价,将x2设为上一年的中位房价(当年减 1)。 - 将
se_x1设为当年中位房价的 MOE 除以Z_CRIT,将se_x2设为上一年对应的同样计算结果。 - 使用 Python 的三元运算符(
result1 if condition else result2):当z的绝对值大于Z_CRIT时返回空字符串,否则返回"not "。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Set the critical Z score for 90% confidence, prepare message
Z_CRIT = 1.645
msg = "Philadelphia median home values in {} were {}significantly different from {}."
for year in range(2012, 2018):
# Assign current and prior year's median home value to variables
x1 = int(philly[philly["year"] == ____]["median_home_value"])
x2 = int(____)
# Calculate standard error as 90% MOE / critical Z score
se_x1 = float(____)
se_x2 = float(____)
# Calculate two-sample z-statistic, output message if greater than critical Z score
z = (x1 - x2) / sqrt(se_x1**2 + se_x2**2)
print(msg.format(year, ____, year - 1))