House Prices · 数据读取与初步分析

上午完成数据读取、售价分布检查、缺失值识别和特征类型整理。代码记录在 project_house_price.ipynb,数据放在项目的 data/raw/ 下。

比赛说明:比赛描述与评分标准。

1. 数据读取

以下相对路径以 notebooks/ 为工作目录,读入两份 CSV:

import pandas as pd
 
train_df = pd.read_csv("../data/raw/train.csv")
test_df = pd.read_csv("../data/raw/test.csv")
 
print(train_df.shape, test_df.shape)

输出:

(1460, 81) (1459, 80)
  • 训练集:1460 行、81 列,包含 Id、79 个解释变量和目标 SalePrice。
  • 测试集:1459 行、80 列,没有 SalePrice。

SalePrice 是实际售价,用于模型训练;Id 用于对应房屋和提交结果。

2. 售价分布

先查看描述性统计:

train_df["SalePrice"].describe()

输出:

count      1460.000000
mean     180921.195890
std       79442.502883
min       34900.000000
25%      129975.000000
50%      163000.000000
75%      214000.000000
max      755000.000000
Name: SalePrice, dtype: float64

均值约 18.09 万,中位数 16.3 万。均值高于中位数,是右偏的线索;直方图可以直接观察分布形状。

import seaborn as sns
 
sns.histplot(data=train_df, x="SalePrice")

SalePrice distribution

房价主要集中在 到 之间,右侧有明显长尾。少数高价房拉高了均值。

对数变换

import math
 
train_df["Ln_SalePrice"] = train_df["SalePrice"].apply(math.log)
sns.histplot(data=train_df, x="Ln_SalePrice")

Log SalePrice distribution

取自然对数后,数据主要集中在 11.5–12.7 附近,右侧长尾减弱,分布更接近对称。

本比赛在对数价格上评分。误差可以写成:

因此,同样比例的价格偏差对评分有相同贡献。对数变换也压缩了高值之间的距离,但保留了原有大小顺序。Ln_SalePrice 是目标的变换,不作为输入特征。

3. 缺失情况

先排除编号、售价和新增的对数售价,对原始特征统计缺失数量和比例:

feature_df = train_df.drop(columns=["Id", "SalePrice", "Ln_SalePrice"])
 
missing_summary = pd.DataFrame({
    "missing_count": feature_df.isna().sum(),
    "missing_ratio": feature_df.isna().mean() * 100,
})
 
missing_summary.sort_values("missing_ratio", ascending=False).head(5)

默认读取设置下的结果,missing_ratio 的单位为百分比:

Fieldmissing_countmissing_ratio (%)
PoolQC145399.520548
MiscFeature140696.301370
Alley136993.767123
Fence117980.753425
MasVnrType87259.726027

isna() 将缺失位置标记为 True。按列求和得到数量,求平均得到比例。

这里需要结合 data_description.txt 判断空值的含义:官方数据说明。

字段含义NA 或 None 的含义
PoolQC泳池质量NA:没有泳池
MiscFeature其他类别未涵盖的附加设施NA:没有该类设施
Alley巷道通行类型NA:没有巷道通行条件
Fence围栏质量NA:没有围栏
MasVnrType砖石贴面类型None:没有贴面;原文件的 NA 为缺失标记

高缺失比例可能对应设施不存在,不能只按比例决定删列。

4. 区分 None 与缺失值

MasVnrType 中的字符串 None 是有效类别,但默认读入时也会被 pandas 识别为缺失。修改读取设置,只将空字符串和 NA 解析为缺失,保留 None:pandas.read_csv。

train_df = pd.read_csv(
    "../data/raw/train.csv",
    keep_default_na=False,
    na_values=["", "NA"],
)
 
test_df = pd.read_csv(
    "../data/raw/test.csv",
    keep_default_na=False,
    na_values=["", "NA"],
)
  • keep_default_na=False:关闭默认缺失标记列表。
  • na_values=["", "NA"]:明确指定缺失标记。

统计 MasVnrType:

for dataset_name, dataset_df in [("train", train_df), ("test", test_df)]:
    none_count = dataset_df["MasVnrType"].eq("None").sum()
    missing_count = dataset_df["MasVnrType"].isna().sum()
 
    print(
        f"{dataset_name}: "
        f"None count={none_count}, missing count={missing_count}"
    )

输出:

train: None count=864, missing count=8
test: None count=878, missing count=16

训练集原先统计出的 872 个缺失中,864 个实际表示没有贴面,只有 8 个是原文件的缺失标记。

重新读入后,表中只包含 CSV 原始列,之前新增的 Ln_SalePrice 不再保留。

5. 特征类型

从重新读入的训练集提取 79 个特征:

feature_df = train_df.drop(columns=["Id", "SalePrice"])
feature_df.info()

输出中的类型统计:

Data columns (total 79 columns):
dtypes: float64(3), int64(33), str(43)

按存储类型,数值列 36 个,字符串列 43 个。

MSSubClass:整数存储的类别

MSSubClass 表示房屋类型,例如:

编码房屋类型
201946 年及以后建造的单层房屋
601946 年及以后建造的双层房屋
90Duplex

编码间没有倍数或距离意义,所以按类别特征处理。将编码映射为数据说明中的文字:

MSSubClass_Map = {
    20: "1-STORY 1946 & NEWER ALL STYLES",
    30: "1-STORY 1945 & OLDER",
    40: "1-STORY W/FINISHED ATTIC ALL AGES",
    45: "1-1/2 STORY - UNFINISHED ALL AGES",
    50: "1-1/2 STORY FINISHED ALL AGES",
    60: "2-STORY 1946 & NEWER",
    70: "2-STORY 1945 & OLDER",
    75: "2-1/2 STORY ALL AGES",
    80: "SPLIT OR MULTI-LEVEL",
    85: "SPLIT FOYER",
    90: "DUPLEX - ALL STYLES AND AGES",
    120: "1-STORY PUD (Planned Unit Development) - 1946 & NEWER",
    150: "1-1/2 STORY PUD - ALL AGES",
    160: "2-STORY PUD - 1946 & NEWER",
    180: "PUD - MULTILEVEL - INCL SPLIT LEV/FOYER",
    190: "2 FAMILY CONVERSION - ALL STYLES AND AGES",
}
 
def convert(number: int) -> str:
    return MSSubClass_Map[number]
 
train_df["MSSubClass"] = train_df["MSSubClass"].apply(convert)
test_df["MSSubClass"] = test_df["MSSubClass"].apply(convert)

映射结果赋回原列,再重新生成特征表并整理两组列名:

feature_df = train_df.drop(columns=["Id", "SalePrice"])
 
numeric_columns = feature_df.select_dtypes(include="number").columns.tolist()
categorical_columns = feature_df.select_dtypes(exclude="number").columns.tolist()
 
print("Train MSSubClass dtype:", train_df["MSSubClass"].dtype)
print("Test MSSubClass dtype:", test_df["MSSubClass"].dtype)
print("Numeric feature count:", len(numeric_columns))
print("Categorical feature count:", len(categorical_columns))

输出:

Train MSSubClass dtype: str
Test MSSubClass dtype: str
Numeric feature count: 35
Categorical feature count: 44

目前保留全部 79 个特征:35 个数值特征、44 个类别特征。缺失值尚未填补。