python 数据分析

python 数据分析

1.数据分析的完整流程

1.数据收集

2.数据清洗

3.数据分析

4.数据可视化

image-20260527094724374

image-20260527094940787

image-20260527095056357

2.anaconda

image-20260527095344053

image-20260527095500340

3.jupyter的使用

image-20260527100244263

image-20260527100319459

image-20260527100342925

image-20260527100356879

image-20260527102231846

4.numpy简绍

image-20260527102441875

image-20260527102617896

5.ndarray的特性

image-20260527110819010

多维性

image-20260527110416925

image-20260527110750131

同质性

image-20260527111144333

6.ndarray的属性

image-20260527111406645

image-20260527111542185

image-20260527113648305

image-20260527114046820

7.ndarray 的创建

image-20260527114423541

image-20260527114924422

image-20260527120704618

image-20260527121032932

image-20260527121129162

image-20260527121214479

image-20260527121326166

image-20260527121506824

image-20260527121850440

image-20260527122046066

image-20260527122251217

image-20260527122423387

image-20260527122543174

image-20260527122652952

image-20260527123108986

image-20260527123345660

image-20260527123544656

image-20260527123827524

8.ndarray 的数据类型

image-20260527123918142

image-20260527124412032

9.索引和切片

image-20260527124539774

image-20260527130214885

image-20260527130757442

image-20260527131427655

10.ndarray 的运算

image-20260527131739560

image-20260527131948840

image-20260527135339184

image-20260527135841219

image-20260527135942420

11.numpy 常用函数

image-20260527173413986

image-20260527174540749

image-20260527174708169

image-20260527175250502

image-20260527175740196

方差和标准差都是统计学中用于衡量数据离散程度(波动大小)的核心指标,二者是平方与开平方的关系‌,方差是标准差的平方,标准差是方差的算术平方根。

指标 定义 作用 特点
‌方差‌ 每个数据与平均值的差的平方的平均数 定量描述数据围绕均值的分散程度(波动大小) 方差越大,数据越分散、波动越大;方差越小,数据越集中、波动越小。但方差单位是原数据单位的平方,不够直观
‌标准差‌ 方差开平方后的结果 反映数据偏离均值的‌平均离散程度‌ 单位与原数据保持一致,比方差更直观易解读

image-20260527180525132

image-20260527181457246

image-20260527182112146

image-20260527182259994

12.numpy 中的比较函数

image-20260527182614380

image-20260527182716676

image-20260527182843511

image-20260527182943357

image-20260527183219892

image-20260527183340437

image-20260527183430032

image-20260527183612550

13.numpy 中的排序函数

image-20260527183830200

image-20260527184042537

image-20260527184218694

image-20260527184305470

14.本章练习

image-20260527185108855

image-20260527185300845

image-20260527185431021

image-20260527185711285

image-20260527190009670

print(score / 10)   #  将成绩转换为(假设满分为10)

image-20260527190306069

image-20260527190502954

image-20260527190538878

np.dot(A, B)   # 计算 A 和 B 的矩阵乘法  等效与  A @ B

image-20260527190939158

image-20260527191513354

image-20260527191613915

image-20260527191658023

image-20260527191953934

image-20260527192022409

image-20260527192140094

image-20260527192215553

image-20260527192505714

image-20260527192541786

image-20260527192646614

image-20260527193110479

image-20260527193429876

image-20260527193747816

15.pandas

image-20260528103913033

image-20260528103955273

image-20260528104021169

image-20260528104034776

image-20260528104252754

image-20260528104721898

image-20260528104828155

16.pandas 中的series

1.series 的创建

image-20260528105124109

image-20260528105523886

image-20260528105628054

image-20260528105748868

image-20260528105950210

2.series属性

image-20260528110034637

image-20260528110833677

3.访问series 数据

image-20260528111548231

4.series 常用方法

image-20260528111624350

image-20260528112003725

image-20260528113023616

image-20260528113339245

image-20260528113622597

image-20260528113725980

image-20260528114237639

image-20260528114701319

案例

image-20260528114945396

image-20260528115625204

image-20260528115648979

image-20260528120134309

image-20260528120513580

image-20260528120722249

image-20260528174716902

image-20260528174743037

image-20260528174759777

image-20260528175125052

image-20260528180441139

image-20260528180519783

image-20260528180557777

image-20260528181634454

17.pandas 中的 DataFrame

image-20260528182203540

image-20260528182502114

1.DataFrame的创建

image-20260528182841541

2.DataFrame 的属性

image-20260528183442466

image-20260528183930661

image-20260528184401848

image-20260528184424187

image-20260528184604068

image-20260528184656890

3.访问 DataFrame的数据

image-20260528185318502

image-20260528185423904

image-20260528185706951

4.DataFrame常见方法

image-20260528185837386

image-20260528185949962

image-20260528190332509

image-20260528190416106

image-20260528191024958

image-20260528191329052

image-20260528191835527

image-20260528191931428

image-20260528192554541

5.DataFrame案例

image-20260528231854058

image-20260528231905613

image-20260528232153837

image-20260528232443654

18.pandas 数据的导入和导出

image-20260528233453593

image-20260528233945991

19.pandas 缺失值的处理

image-20260529084050036

image-20260529085114742

20.pandas数据类型转换

数据的去重

image-20260529085630921

image-20260529090004617

21.pandas数据变形

image-20260529090640197

image-20260529091434122

22.pandas 数据分箱

image-20260529092543377

image-20260529093003119

image-20260529093421895

23.pandas 时间数据的处理

image-20260529135736931

image-20260529140221512

image-20260529140538517

image-20260529141521237

image-20260529141817621

image-20260529142034932

24.pandas分组聚合

image-20260529143206417

25.pandas 综合案例

image-20260529144322961

image-20260529145156633

image-20260529145212746

26.数据可视化

image-20260530043743307

image-20260530044028004

image-20260530044243469

image-20260530044400385

image-20260530044509620

image-20260530044652998

27.matplotlib-折线图

image-20260530045854317

# 绘制折线图
import matplotlib.pyplot as plt
from matplotlib import rcParams # 字体
# rcParams['font.family'] = 'STHeiti' #mac  win:SimHei
rcParams['font.sans-serif'] = 'SimHei'
# 创建图表,设置大小
plt.figure(figsize=(10,5))

# 要绘图的数据
month = ['1月','2月','3月','4月']
sales = [100,150,80,130]
# 绘制折线图
plt.plot(month,sales,
         label='产品A',
         color='orange',
         linewidth=2,
         linestyle='--',
         marker='o',)

# 添加标题
plt.title('2025年销售趋势', color='red',fontsize=20)
# 添加坐标轴的标签
plt.xlabel('月份',fontsize=10)
plt.ylabel('销售额(万元)',fontsize=10)
# 添加图例
plt.legend(loc='upper left')
# 添加网格线
plt.grid(True,alpha=0.1,color='blue',linestyle='--')
# plt.grid(axis='x')
# 设置刻度字体大小
plt.xticks(rotation=0,fontsize=12)
plt.yticks(rotation=0,fontsize=12)
# 设置y轴的范围
plt.ylim(0,160)
# 在每个数据点上显示数值
for x,y in zip(month,sales):
    plt.text(x,y+1,str(y),ha='center',va='bottom',fontsize=10)
# 显示图表
plt.show()

image-20260530051458216

28.matplotlib-柱状图

# 绘制柱状图
import matplotlib.pyplot as plt
from matplotlib import rcParams # 字体
# rcParams['font.family'] = 'STHeiti' #mac  win:SimHei
rcParams['font.sans-serif'] = 'SimHei'
# 创建图表,设置大小
plt.figure(figsize=(10,5))

# 要绘图的数据
subjects = ['语文','数学','英语','科学']
scores = [85, 92, 78, 88]

# 绘制柱状图
plt.bar(subjects,scores,
        label='小红',
        color='orange',
        width=0.6,)
#
# 添加标题
plt.title('2025年成绩分布', color='red',fontsize=20)
# 添加坐标轴的标签
plt.xlabel('科目',fontsize=10)
plt.ylabel('分数',fontsize=10)
# 添加图例
plt.legend(loc='upper right')
# 添加网格线
plt.grid(axis='y',alpha=0.1,color='blue',linestyle='--')
# plt.grid(axis='x')
# 设置刻度字体大小
plt.xticks(rotation=0,fontsize=12)
plt.yticks(rotation=0,fontsize=12)
# 设置y轴的范围
plt.ylim(0,100)
# 在每个数据点上显示数值
for x,y in zip(subjects,scores):
    plt.text(x,y+1,str(y),ha='center',va='bottom',fontsize=10)
# 自动优化排版
plt.tight_layout()
# 显示图表
plt.show()

image-20260530052357697

29.matplotlib-条形图

# 绘制条形图
import matplotlib.pyplot as plt
from matplotlib import rcParams # 字体
# rcParams['font.family'] = 'STHeiti' #mac  win:SimHei
rcParams['font.sans-serif'] = 'SimHei'
# 创建图表,设置大小
plt.figure(figsize=(10,5))

# 要绘图的数据
countries = ['United States','China','Japan','Germany','India']
gdp = [ 92,78, 43, 22,8]
#
# 绘制条形图
plt.barh(countries,gdp,color='orange',)

# 添加标题
plt.title('2025年GDP排名', color='red',fontsize=20)
# 添加坐标轴的标签
plt.xlabel('GDP',fontsize=10)
plt.ylabel('国家',fontsize=10)
# 自动优化排版
plt.tight_layout()
# 显示图表
plt.show()

image-20260530053011174

30.matplotlib-饼图

# 绘制饼图
import matplotlib.pyplot as plt
from matplotlib import rcParams # 字体
# rcParams['font.family'] = 'STHeiti' #mac  win:SimHei
rcParams['font.sans-serif'] = 'SimHei'
# 创建图表,设置大小
plt.figure(figsize=(10,5))
# 要绘图的数据
things = ['学习','娱乐','运动','睡觉','其他']
times = [6,4,1,8,5]
colors = ['#66b3ff','#99ff99','#ffcc99','#ff9999','#ff4499']  #配色
# 绘制饼图
plt.pie(times,labels=things,
        autopct='%.1f%%',  # 显示百分比
        startangle=90, #调整初始画图的角度
        colors = colors,
        )
# 添加标题
plt.title('一天的时间分布', color='red',fontsize=20)
# 自动优化排版
plt.tight_layout()
# 显示图表
plt.show()

image-20260530053713159

matplotlib-环形图(饼图变形)

# 绘制环形图
import matplotlib.pyplot as plt
from matplotlib import rcParams # 字体
# rcParams['font.family'] = 'STHeiti' #mac  win:SimHei
rcParams['font.sans-serif'] = 'SimHei'
# 创建图表,设置大小
plt.figure(figsize=(10,5))
# 要绘图的数据
things = ['学习','娱乐','运动','睡觉','其他']
times = [6,4,1,8,5]
colors = ['#66b3ff','#99ff99','#ffcc99','#ff9999','#ff4499']  #配色
# 绘制饼图
plt.pie(times,labels=things,
        autopct='%.1f%%',  # 显示百分比
        startangle=90, #调整初始画图的角度
        colors = colors,# 设置饼图的配色
        wedgeprops={'width':0.6},#设置圆环的宽度
        pctdistance=0.6, #设置百分比的位置
        )
# 添加标题
plt.title('一天的时间分布', color='red',fontsize=20)
plt.text(0,0,'总计:\n100%',ha='center',va='bottom',fontsize=10)
# 自动优化排版
plt.tight_layout()
# 显示图表
plt.show()

image-20260530054026329

matplotlib- 爆炸式饼图

# 绘制爆炸式饼图
import matplotlib.pyplot as plt
from matplotlib import rcParams # 字体
# rcParams['font.family'] = 'STHeiti' #mac  win:SimHei
rcParams['font.sans-serif'] = 'SimHei'
# 创建图表,设置大小
plt.figure(figsize=(10,5))
# 要绘图的数据
things = ['学习','娱乐','运动','睡觉','其他']
times = [6,4,1,8,5]
colors = ['#66b3ff','#99ff99','#ffcc99','#ff9999','#ff4499']  #配色
explode = [0.1,0,0,0,0]#设置突出块的位置
# 绘制饼图
plt.pie(times,labels=things,
        autopct='%.1f%%',  # 显示百分比
        startangle=0, #调整初始画图的角度
        colors = colors,
        explode = explode,#设置突出块
        shadow=True,
        )
# 添加标题
plt.title('一天的时间分布', color='red',fontsize=20)
# 自动优化排版
plt.tight_layout()
# 显示图表
plt.show()

image-20260530054455408

31.matplotlib-散点图

# 绘制散点图
import matplotlib.pyplot as plt
from matplotlib import rcParams # 字体
# rcParams['font.family'] = 'STHeiti' #mac  win:SimHei
rcParams['font.sans-serif'] = 'SimHei'
# 创建图表,设置大小
plt.figure(figsize=(10,5))

# 要绘图的数据
scores=[50,55,60,65,70,75,80]
hours=[1,2,3,4,5,6,7]

# 绘制散点图
plt.scatter(hours,scores)

# 显示图表
plt.show()

image-20260530055349945

32.matplotlib-箱线图

image-20260530055434016

# 箱线图
import matplotlib.pyplot as plt

# 模拟 3 门课的成绩
data = {
    '语文': [82, 85, 88, 70, 90, 76, 84, 83, 95],
    '数学': [75, 80, 79, 93, 88, 82, 87, 89, 92],
    '英语': [70, 72, 68, 65, 78, 80, 85, 90, 95]
}
plt.figure(figsize=(8, 6))
plt.boxplot(data.values(), labels=data.keys())

plt.title("各科成绩分布(箱线图)")
plt.ylabel("分数")
plt.grid(True, axis='y', linestyle='--', alpha=0.5)
plt.show()

image-20260530060117718

'''
折线图:趋势随时间变化
条形图/柱状图:类别之间对比
饼图:整体组成比例
散点图:两变量相关性
箱线图:数据分布、异常
'''

33.matplotlib-多个图表的绘制

# 多个图的绘制方法
import matplotlib.pyplot as plt
# 要绘图的数据
month = ['1','2','3','4']
sales = [100,150,80,130]

# 动态图表的生成
# f1 = plt.subplot(2,2,1) #生成一个子图 行 列 索引
f1 = plt.subplot(221) #生成一个子图 行 列 索引
f1.plot(month,sales)
f2 = plt.subplot(2,2,2)
f2.bar(month,sales)
f3 = plt.subplot(2,2,3)
f3.scatter(month,sales)
f4 = plt.subplot(224)
f4.barh(month,sales)

image-20260530060645784

34.matplotlib-综合案例

# 分析案例:温度分析
# 1. 导入库
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.sans-serif'] = 'Microsoft YaHei'

# 2. 导入数据
df = pd.read_csv('data/weather.csv')
df.head()
# 绘制气温的趋势变化图
df['date'] = pd.to_datetime(df['date'])
df=df[df['date'].dt.year==2015]
plt.figure(figsize=(15,10))
plt.plot(df['date'],df['temp_max'],label='最高气温')
plt.plot(df['date'],df['temp_min'],label='最低气温')
plt.title('2015年气温趋势变化图')
plt.xlabel('日期')
plt.ylabel('气温')
plt.legend()

image-20260530062423373

# 分析案例:温度分析
# 1. 导入库
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.sans-serif'] = 'Microsoft YaHei'

# 2. 导入数据
df = pd.read_csv('data/weather.csv')
df.head()
# 绘制气温的趋势变化图
df['date'] = pd.to_datetime(df['date'])
df=df[df['date'].dt.year==2015]
plt.figure(figsize=(15,10))

# 绘制气温的趋势变化图 平均气温
df['temp_mean'] = (df['temp_max'] + df['temp_min'])/2
plt.figure(figsize=(15,10))
plt.plot(df['date'],df['temp_mean'],label='平均气温')
plt.title('2015年气温趋势变化图')
plt.xlabel('日期')
plt.ylabel('气温')
plt.legend()

image-20260530062737564

直方图

# 分析案例:温度分析
# 1. 导入库
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.sans-serif'] = 'Microsoft YaHei'

# 2. 导入数据
df = pd.read_csv('data/weather.csv')
df.head()
# 绘制气温的趋势变化图
df['date'] = pd.to_datetime(df['date'])
df=df[df['date'].dt.year==2015]
plt.figure(figsize=(15,10))

# 绘制降水量的直方图
plt.hist(df['precipitation'],bins=5)

image-20260530062853865

35.seaborn学习

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]
penguins = pd.read_csv("data/penguins.csv")
penguins.dropna(inplace=True)
penguins.info()
penguins.head()
# 直方图
sns.histplot(data=penguins, x="species")

image-20260530105621681

#核密度估计图
'''核密度估计图(KDE,Kernel Density Estimate Plot)是一种用于显示数据分布的统计图表,它通过平滑直方图的方法来估计数据的概率密度函数,使得分布图看起来更加连续和平滑。核密度估计是一种非参数方法,用于估计随机变量的概率密度函数。其基本思想是,将每个数据点视为一个“核”(通常是高斯分布),然后将这些核的贡献相加以形成平滑的密度曲线。'''
#绘制喙长度的核密度估计图
sns.kdeplot(data=penguins, x="bill_length_mm")

image-20260530105851218

sns.histplot(data=penguins, x="bill_length_mm", kde=True)

image-20260530105915095

'''计数图
计数图用于绘制分类变量的计数分布图,显示每个类别在数据集中出现的次数,是分析分类数据非常直观的工具,可以快速了解类别的分布情况。'''
#绘制不同岛屿企鹅数量的计数图
sns.countplot(data=penguins, x="island")

image-20260530110054485

#散点图
#绘制横轴为体重,纵轴为脚蹼长度的散点图。可通过hue参数设置不同组别进行对比
sns.scatterplot(data=penguins, x="body_mass_g", y="flipper_length_mm", hue="sex")

image-20260530110125797

#蜂窝图
#通过jointplot()函数,设置kind="hex"来绘制蜂窝图。
sns.jointplot(data=penguins, x="body_mass_g", y="flipper_length_mm", kind="hex")

image-20260530110321750

#二维核密度估计图
#通过kdeplot()函数,同时设置x参数和y参数来绘制二维核密度估计图。
sns.kdeplot(data=penguins, x="body_mass_g", y="flipper_length_mm")

image-20260530110404544

#通过fill=True设置为填充,通过cbar=True设置显示颜色示意条。
sns.kdeplot(data=penguins, x="body_mass_g", y="flipper_length_mm", fill=True, cbar=True)

image-20260530110440979

#条形图
sns.barplot(data=penguins, x="species", y="bill_length_mm", estimator="mean", errorbar=None)

image-20260530110504996

#箱线图
sns.boxplot(data=penguins, x="species", y="bill_length_mm")

image-20260530110528289

#小提琴图
'''小提琴图(Violin Plot) 是一种结合了箱线图和核密度估计图(KDE)的可视化图表,用于展示数据的分布情况、集中趋势、散布情况以及异常值。小提琴图不仅可以显示数据的基本统计量(如中位数和四分位数),还可以展示数据的概率密度,提供比箱线图更丰富的信息。'''
sns.violinplot(data=penguins, x="species", y="bill_length_mm")

image-20260530110559344

#成对关系图
'''成对关系图是一种用于显示多个变量之间关系的可视化工具。它可以展示各个变量之间的成对关系,并且通过不同的图表形式帮助我们理解数据中各个变量之间的相互作用。
对角线上的图通常显示每个变量的分布(如直方图或核密度估计图),帮助观察每个变量的单变量特性。其他位置展示所有变量的两两关系,用散点图表示。'''
sns.pairplot(data=penguins, hue="species")

image-20260530110921886

36.项目

1.项目简绍

项目实战:房地产市场洞察与价值评估

数据分析流程

采集数据→确定分析方向→导入数据→数据清洗→数据分析→数据可视化

数据源介绍

字段名 含义 说明
city 城市 房屋所在的城市名称,例如“合肥”、“重庆”等。
address 详细地址 房屋的具体位置,包含街道、交叉口等信息。
area 面积 房屋的面积,单位为平方米(㎡)。
floor 楼层 房屋所在的楼层信息,例如“中层(共18层)”。
name 小区名称 房屋所在的小区或楼盘名称。
price 价格 房屋的总价,单位为“万”或“元”。
province 省份 房屋所在的省份或直辖市名称。
rooms 户型 房屋的户型结构,例如“3室2厅”。
toward 朝向 房屋的朝向,例如“南北向”、“南向”等。
unit 单价 房屋的单价,单位为“元/㎡”。
year 建造年份 房屋的建造年份,例如“2013年建”。
origin_url 原始链接 房屋信息的来源网页链接。

分析及统计问题

编号 问题 分析主题 分析目标 分组字段 指标/方法
A1 哪些变量最影响房价?面积、楼层、房间数哪个影响更大? 特征相关性 了解房屋各特征对房价的线性影响 皮尔逊相关系数
A2 全国房价总体分布是怎样的?是否存在极端值? 描述性统计 概览数值型字段的分布特征 平均数/中位数/四分位数/标准差
A3 哪些城市房价最高?直辖市与非直辖市差异如何? 城市对比 比较不同城市房价水平 city 均价/单价中位数/箱线图
A4 高价房在面积、楼层等方面有什么特征? 价格分层 识别不同价位房屋特征差异 价格分段(低中高) 列联表/卡方检验
A5 哪种户型最受欢迎?三室比两室贵多少? 户型分析 分析不同户型的市场表现 rooms 占比/平均单价/溢价率
A6 南北向是否真比单一朝向贵?贵多少? 朝向溢价 评估不同朝向的价格差异 toward 方差分析/多重比较
A7 新房比10年老房贵多少?折旧规律如何? 楼龄效应 研究建筑年份对房价的影响 year分段(5年间隔) 趋势线/回归分析
A8 哪些区域交易最活跃?新区和老城区哪个更贵? 区域热度 识别各城市热门交易区域 address(提取区域关键词) 交易量/价格增长率
A9 哪个面积段的性价比最高?超大户型有溢价吗? 面积区间 分析不同面积段的价格特征 area分段(50㎡间隔) 密度图/价格梯度
A10 中层真的比高层贵吗?差价是多少? 楼层差异 比较不同楼层的价格表现 floor(高中低层) Kruskal-Wallis检验
A11 直辖市房价是否显著更高?单价和总价差异如何? 直辖市vs非直辖市 对比直辖市与非直辖市的房价差异 province 独立样本t检验/曼-惠特尼U检验

2.数据类型转换

# 1. 导入库
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib import rcParams
rcParams['font.sans-serif'] = ['SimHei'] #win
# rcParams['font.sans-serif'] = ['STHeiti'] #mac
#%%
# 2. 导入数据
df = pd.read_csv('data/house_sales.csv')
#%%
# 3. 数据概览
print('总记录数:', len(df))
print('字段数量:', len(df.columns))
df.head(5)
# df.info()

#%%
# 4. 数据清洗
# 删除无用的数据列
df.drop(columns='origin_url',inplace=True)
#%%
# 检查是否有缺失值
df.isna().sum()
# 删除缺失值
df.dropna(inplace=True)
#%%
# 检查是否有重复值
df.duplicated().sum()
# 删除重复数据
df.drop_duplicates(inplace=True)
# print(len(df))
# 面积的数据类型转换
df['area'] = df['area'].astype(str).str.replace('㎡','').astype(float)
# 售价的数据类型转换
df['price'] = df['price'].astype(str).str.replace('万','').astype(float)
# 朝向的数据类型转换
df['toward'] = df['toward'].astype('category')
# 单价的数据类型转换
df['unit'] = df['unit'].astype(str).str.replace('元/㎡','').astype(float)
# 建造年份的数据类型转换
df['year'] = df['year'].astype(str).str.replace('年建','').astype(int)

df.head()

数据的变化

image-20260530115731224

image-20260530115631475

3.异常值处理

# 异常值的处理
# 房屋面积的异常处理
df = df[ (df['area']<600) & (df['area']>20)]
#%%
# 房屋售价的异常处理  IQR
Q1 = df['price'].quantile(0.25)
Q3 = df['price'].quantile(0.75)
IQR = Q3 - Q1
low_price = Q1 - 1.5*IQR
high_price = Q3 + 1.5*IQR
df = df[ (df['price']<high_price) & (df['price']>low_price) ]

4.数据特征构造

# 5. 新数据特征构造
# 地区district
df['district'] = df['address'].str.split('-').str[0]
# 楼层的类型floor_type
df['floor_type'] = df['floor'].str.split('(').str[0].astype('category')
def fun1(str1):
    if pd.isna(str1):
        return '未知'
    elif '低' in str1:
        return '低楼层'
    elif '中' in str1:
        return '中楼层'
    elif '高' in str1:
        return '高楼层'
    else:
        return '未知'
df['floor_type2'] = df['floor'].apply(fun1).astype('category')
# 是否是直辖市zxs
df['zxs'] = df['city'].apply(lambda x: 1 if x in ['北京','上海','天津','重庆'] else 0)
# 卧室的数量bedrooms
df['bedrooms'] = df['rooms'].str.split('室').str[0].astype(int)
# 客厅的数量livingrooms
# df['rooms'].str.split('室').str[1].str.split('厅').str[0].astype(int)
df['livingrooms'] = df['rooms'].str.extract(r'(\d+)厅').astype('int')
# 楼龄building_age
df['building_age'] = 2025 - df['year']
# 价格的分段price_labels
df['price_labels'] = pd.cut(df['price'],bins=4,labels=['低价','中价','高价','豪华'])
#%%

5.特征相关值

'''
问题编号: A1
问题: 哪些变量最影响房价?面积、楼层、房间数哪个影响更大?
分析主题: 特征相关性
分析目标: 了解房屋各特征对房价的线性影响
分组字段: 无
指标/方法: 皮尔逊相关系数
'''
# 选择数值型特征
a = df[['price','area','unit','building_age']].corr()#相关系数
# 对房价的影响最大的几个因素的排序
a['price'].sort_values(ascending=False)[1:]
# 相关性的热力图
plt.figure(figsize = (5,5))
sns.heatmap(a,cmap='coolwarm')
plt.title('房屋特征相关性热力图')
plt.tight_layout()
# df.head()

image-20260530171409706

6.房价分布直方图

'''
问题编号: A2
问题: 全国房价总体分布是怎样的?是否存在极端值?
分析主题: 描述性统计
分析目标: 概览数值型字段的分布特征
分组字段: 无
指标/方法: 平均数/中位数/四分位数/标准差
'''
df.describe()
# 房价分布直方图
plt.subplot(111)
plt.hist(df['price'],bins=10)
df.head()
sns.histplot(data=df,x='price',bins=10,kde=True)
# sns.histplot(data=df,x='price',kde=True)

image-20260530171903617

7.朝向分析

'''
问题编号: A6
问题: 南北向是否真比单一朝向贵?贵多少?
分析主题: 朝向溢价
分析目标: 评估不同朝向的价格差异
分组字段: toward
指标/方法: 方差分析/多重比较
'''
df['toward'].value_counts()
df.groupby('toward').agg({
    'price':['mean','median'],
    'unit':'median',
    'building_age':'mean',
})
# 数据可视化
plt.figure(figsize=(14, 5))
sns.boxplot(x='toward', y='price', data=df)
plt.tight_layout()

image-20260530172445077

8-其他

'''
问题编号: A3
问题: 哪些城市房价最高?直辖市与非直辖市差异如何?
分析主题: 城市对比
分析目标: 比较不同城市房价水平
分组字段: city
指标/方法: 均价/单价中位数/箱线图
'''
# 按城市统计
city_stats = df.groupby('city').agg({
    'price': ['mean', 'median', 'count'],
    'unit': ['mean', 'median']
})
print("\n各城市房价统计:")
display(city_stats.sort_values(('unit', 'mean'), ascending=False).head(10))

# 可视化前10城市
top_cities = city_stats.sort_values(('unit', 'mean'), ascending=False).head(10).index
df_top = df[df['city'].isin(top_cities)]

plt.figure(figsize=(12, 6))
sns.boxplot(x='city', y='price', data=df_top, order=top_cities)
plt.title('TOP10城市房价分布对比', fontsize=14)
plt.xlabel('城市')
plt.ylabel('价格(元)')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

image-20260530172534611

image-20260530172550364

'''
问题编号: A4
问题: 高价房在面积、楼层等方面有什么特征?
分析主题: 价格分层
分析目标: 识别不同价位房屋特征差异
分组字段: 价格分段(低中高)
指标/方法: 列联表/卡方检验
'''
"""A4 价格分层特征差异分析"""
print("\n=== A4 价格分层特征差异 ===")

# 按价格分段分析特征
price_group = df.groupby('price_labels').agg({
    'area': ['mean', 'median'],
    'building_age': 'mean',
    'unit': 'median',
    'zxs': 'mean'  # 直辖市占比
})

print("\n各价格层级特征对比:")
display(price_group)

# 可视化
plt.figure(figsize=(14, 5))

plt.subplot(131)
sns.barplot(x='price_labels', y='area', data=df, estimator=np.median)
plt.title('不同价格层级面积对比')
plt.ylabel('面积(㎡)')

plt.subplot(132)
sns.boxplot(x='price_labels', y='building_age', data=df)
plt.title('不同价格层级楼龄分布')
plt.ylabel('楼龄(年)')


plt.tight_layout()
plt.show()

image-20260530172625681

'''
问题编号: A5
问题: 哪种户型最受欢迎?三室比两室贵多少?
分析主题: 户型分析
分析目标: 分析不同户型的市场表现
分组字段: rooms
指标/方法: 占比/平均单价/溢价率
'''
"""A5 户型市场表现分析"""
print("\n=== A5 户型分析 ===")

# 提取房间数(示例:"3室2厅" -> 3)
df['room_count'] = df['rooms'].str.extract('(\d+)室').astype(float)

# 按户型统计
room_stats = df.groupby('room_count').agg({
    'price': ['mean', 'median'],
    'unit': 'median',
    'area': 'median',
    'city': 'nunique'
}).sort_values(('price', 'mean'))

print("\n各户型市场表现:")
display(room_stats)

# 可视化
plt.figure(figsize=(14, 5))

plt.subplot(131)
sns.boxplot(x='room_count', y='price', data=df)
plt.title('不同户型总价分布')
plt.xlabel('房间数')

plt.subplot(132)
sns.scatterplot(x='area', y='price', hue='room_count', data=df, palette='viridis')
plt.title('面积-价格-户型关系')

plt.subplot(133)
sns.barplot(x='room_count', y='unit', data=df, estimator=np.median)
plt.title('不同户型单价对比')
plt.xlabel('房间数')

plt.tight_layout()
plt.show()

image-20260530172658120

posted @ 2026-05-31 16:07  Ref-brief  阅读(4)  评论(2)    收藏  举报