Python专区 加入小组

135个成员 36个话题 创建时间:2019-12-17

帝都房价回调?带你用Python了解北京二手房市场现状文章代码

发表于2020-08-10 1858次查看

二手房数据分析
Apply kdd process in ershoufang data analysis.
数据读入

# 导入所需包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os  


from pyecharts.charts import Pie, Map, Bar, Line, Grid, Page
from pyecharts import options as opts


import plotly as py
import plotly.graph_objs as go
import plotly.express as px
from plotly import tools
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
plt.style.use('seaborn')
# 读入数据
file_list = os.listdir('../data/')
​
df_all = pd.DataFrame()
for file in file_list:
    file_name = file.split('.')[0]
    print(f'读入 {file_name} 的房价数据')
    df = pd.read_csv(f'../data/{file}')
    df['region_name'] = file_name
    df_all = df_all.append(df, ignore_index=True)
    
print(df_all.shape)

 

读入 东城 的房价数据
读入 丰台 的房价数据
读入 大兴 的房价数据
读入 密云 的房价数据
读入 平谷 的房价数据
读入 延庆 的房价数据
读入 怀柔 的房价数据
读入 房山 的房价数据
读入 昌平 的房价数据
读入 朝阳 的房价数据
读入 海淀 的房价数据
读入 石景山 的房价数据
读入 西城 的房价数据
读入 通州 的房价数据
读入 门头沟 的房价数据
读入 顺义 的房价数据
(33570, 9)

 

# 重复值
df_all.duplicated().sum()
​
# 去重
df_all = df_all.drop_duplicates()
df_all.info()

 

<class 'pandas.core.frame.DataFrame'>
Int64Index: 33509 entries, 0 to 33569
Data columns (total 9 columns):
 #   Column       Non-Null Count  Dtype
---  ------       --------------  -----
 0   title        33509 non-null  object
 1   detail_url   33509 non-null  object
 2   position     33509 non-null  object
 3   houseInfo    33509 non-null  object
 4   followInfo   33509 non-null  object
 5   tag_info     33509 non-null  object
 6   total_price  33509 non-null  object
 7   unitPrice    33509 non-null  object
 8   region_name  33509 non-null  object
dtypes: object(9)
memory usage: 2.6+ MB


数据预处理
初步处理-进一步处理

title:无需分析,删除
detail_url:无需分析,删除
position:维度过细、删除
houseInfo:提取室、厅、面积、方位、装修、楼层(高中低)、建筑年份、板塔
followInfo:无需分析,删除
tag_info:提取是否靠近地铁
total_price:提取房屋总价
unitPrice:房屋单价
region_name:无需处理

# 删除列
df_all = df_all.drop(['title', 'detail_url', 'position', 'followInfo'], axis=1)  
​
# 提取室厅
df_all['halls'] = df_all['houseInfo'].str.split('|').str[0].str.extract(r'(\d+)室')
df_all['bedrooms'] = df_all['houseInfo'].str.split('|').str[0].str.extract(r'\d室(\d+)厅')
# 提取面积
df_all['area'] = df_all['houseInfo'].str.split('|').str[1].str.extract(r'(\d+.*\d+)平米')
# 提取朝向
df_all['orient'] = df_all['houseInfo'].str.split('|').str[2]
# 提取装修类型
df_all['decorate_type'] = df_all['houseInfo'].str.split('|').str[3]
# 提取楼层
df_all['floor'] = df_all['houseInfo'].str.split('|').str[4]
# 提取建筑年份
df_all['built_year'] = df_all['houseInfo'].str.split('|').str[5].str.extract(r'(\d+)')
# 提取板塔
df_all['banta'] = df_all['houseInfo'].str.split('|').str[6]
# 删除houseInfo
df_all = df_all.drop('houseInfo', axis=1)
​
# 提取地铁
df_all['subway'] = [1 if '地铁' in i else 0 for i in df_all['tag_info']]
# 删除tag_info
df_all = df_all.drop('tag_info', axis=1)
​
# 提取总价
df_all['total_price'] = df_all['total_price'].str.extract(r'(\d+)')
df_all['unitPrice'] = df_all['unitPrice'].str.extract(r'(\d+)')
​
# 空值-直接删除
df_all = df_all.dropna()
​
# 转换数据类型
df_all['total_price'] = df_all['total_price'].astype('int')
df_all['unitPrice'] = df_all['unitPrice'].astype('int')
df_all['halls'] = df_all['halls'].astype('int')
df_all['bedrooms'] = df_all['bedrooms'].astype('int')
df_all['area'] = df_all['area'].astype('float')
df_all['built_year'] = df_all['built_year'].astype('int')
df_all['subway'] = df_all['subway'].astype('int')
df_all.head()


total_price    unitPrice    region_name    halls    bedrooms    area    orient    decorate_type    floor    built_year    banta    subway
0    645    104810    东城    2    1    61.54    东 北    精装    中楼层(共22层)    2010    板塔结合    0
1    564    97866    东城    2    1    57.63    东 西    精装    低楼层(共7层)    1988    板楼    0
2    740    110448    东城    2    1    67.00    东 南 北    简装    高楼层(共6层)    2003    板楼    1
3    635    103185    东城    2    1    61.54    东北    精装    顶层(共22层)    2010    板塔结合    0
4    880    95694    东城    3    1    91.96    南 北    简装    中楼层(共16层)    2003    板塔结合    0

def transform_floor(x):
    if x == '高楼层' or x == '顶层' or x == '上叠':
        return '高层'
    elif x == '低楼层' or x == '底层' or x == '下叠' or x == '1层' or x == '2层' or x == '3层':
        return '低层'
    elif x == '中楼层' or x == '4层' or x == '5层' or x == '6层':
        return '中层'
    elif x == '地下室':
        return '地下室'
    else:  # 其他归为高层
        return '高层'  
​
# floor一般化
df_all['floor_type'] = df_all['floor'].str.replace(r'\(.*?\)', '').str.strip()
df_all['floor_type'] = df_all.floor_type.apply(transform_floor)
df_all = df_all.drop('floor', axis=1)
​
# orient-一般化
df_all['orient'] = df_all['orient'].str.extract(r'([\u4e00-\u9fa5])')
​
# bulit_year
df_all['built_year'] = 2020 - df_all['built_year']
​
# banta-一般化
df_all['banta'] = df_all.banta.str.strip()
df_all.head()


total_price    unitPrice    region_name    halls    bedrooms    area    orient    decorate_type    built_year    banta    subway    floor_type
0    645    104810    东城    2    1    61.54    东    精装    10    板塔结合    0    中层
1    564    97866    东城    2    1    57.63    东    精装    32    板楼    0    低层
2    740    110448    东城    2    1    67.00    东    简装    17    板楼    1    高层
3    635    103185    东城    2    1    61.54    东    精装    10    板塔结合    0    高层
4    880    95694    东城    3    1    91.96    南    简装    17    板塔结合    0    中层

df_all.info()

 

<class 'pandas.core.frame.DataFrame'>
Int64Index: 32448 entries, 0 to 33569
Data columns (total 12 columns):
 #   Column         Non-Null Count  Dtype  
---  ------         --------------  -----  
 0   total_price    32448 non-null  int32  
 1   unitPrice      32448 non-null  int32  
 2   region_name    32448 non-null  object
 3   halls          32448 non-null  int32  
 4   bedrooms       32448 non-null  int32  
 5   area           32448 non-null  float64
 6   orient         32448 non-null  object
 7   decorate_type  32448 non-null  object
 8   built_year     32448 non-null  int32  
 9   banta          32448 non-null  object
 10  subway         32448 non-null  int32  
 11  floor_type     32448 non-null  object
dtypes: float64(1), int32(6), object(5)
memory usage: 2.5+ MB


数据探索和可视化
北京二手房房价走势图

month_num = ['2019.09月', '2019.10月', '2019.11月', '2019.12月', '2020.01月',
             '2020.02月', '2020.03月', '2020.04月', '2020.05月', '2020.06月',
             '2020.08月', '2020.09月']
price_num = [59590, 59126, 58540, 58568, 58439,
             58150, 58435, 58605, 58352, 58227,
             58096, 57589]
# 折线图
line2 = Line(init_opts=opts.InitOpts(width='1350px', height='750px'))
line2.add_xaxis(month_num)
line2.add_yaxis('', price_num,
                label_opts=opts.LabelOpts(is_show=True),
#                 markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="min"),
#                                                         opts.MarkPointItem(type_="max"),]),
               )   
line2.set_global_opts(title_opts=opts.TitleOpts(title='近一年北京二手房房价走势图(元/平米)'),
                      visualmap_opts=opts.VisualMapOpts(max_=59590),
#                       xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate='45')),
                      yaxis_opts=opts.AxisOpts(
                        max_=60000,
                        min_=57000,
                        name="",
                        type_="value",
                        axislabel_opts=opts.LabelOpts(formatter="{value}"),
                        splitline_opts=opts.SplitLineOpts(is_show=False),   
                    )
                     )
line2.set_series_opts(linestyle_opts=opts.LineStyleOpts(width=3))
line2.render('./html/近一年北京二手房房价走势图.html')


'C:\\Users\\wzd\\Desktop\\CDA\\CDA_Python\\Python项目实作\\房价分析\\链家网\\code\\html\\近一年北京二手房房价走势图.html'
北京二手房都处在哪些价位?

bins = [74, 300, 500, 800, 1000, 8299]
bins_label = ['300万及以下', '300-500万', '500-800万', '800-1000万', '1000万以上']
​
df_all['price_cut'] = pd.cut(df_all['total_price'], bins=bins, labels=bins_label)
df_all.head()


total_price    unitPrice    region_name    halls    bedrooms    area    orient    decorate_type    built_year    banta    subway    floor_type    price_cut
0    645    104810    东城    2    1    61.54    东    精装    10    板塔结合    0    中层    500-800万
1    564    97866    东城    2    1    57.63    东    精装    32    板楼    0    低层    500-800万
2    740    110448    东城    2    1    67.00    东    简装    17    板楼    1    高层    500-800万
3    635    103185    东城    2    1    61.54    东    精装    10    板塔结合    0    高层    500-800万
4    880    95694    东城    3    1    91.96    南    简装    17    板塔结合    0    中层    800-1000万

price_num = df_all.price_cut.value_counts()
# 数据对
data_pair = [list(z) for z in zip(price_num.index.tolist(), price_num.values.tolist())]
data_pair


[['300-500万', 11647],
 ['500-800万', 8612],
 ['300万及以下', 6339],
 ['1000万以上', 3362],
 ['800-1000万', 2487]]

# 绘制饼图
pie1 = Pie(init_opts=opts.InitOpts(width='1350px', height='750px'))
pie1.add('', data_pair=data_pair, radius=['30%', '60%'], rosetype='radius')
pie1.set_global_opts(title_opts=opts.TitleOpts(title='北京二手房都处在哪些价位?'),
                     legend_opts=opts.LegendOpts(orient='vertical', pos_top='15%', pos_left='2%'))
pie1.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}:{d}%"))
pie1.set_colors(['#FF7F0E', '#1F77B4', '#2CA02C', '#D62728', '#946C8B'])
pie1.render('./html/北京二手房都处在哪些价位.html')


'C:\\Users\\wzd\\Desktop\\CDA\\CDA_Python\\Python项目实作\\房价分析\\链家网\\code\\html\\北京二手房都处在哪些价位.html'
北京不同区域的二手房房源数量-链家

# 来源:链家网
region_name = ['东城', '西城', '朝阳', '海淀', '丰台',
               '石景山', '通州', '昌平', '大兴', '顺义',
               '房山', '门头沟', '平谷', '怀柔', '密云',
               '延庆']
​
house_num = [3583, 6394, 25648, 9788, 11094,
             2075, 6872, 7959, 7187, 5115,
             4618, 1219, 116, 40, 186,
             14]
# 数据框
df_region = pd.DataFrame({
    'region_name': region_name,
    'house_num': house_num
})
df_region = df_region.sort_values('house_num', ascending=False)
​
# 产生数据
x_data = df_region['region_name'].values.tolist()
y_data = df_region['house_num'].values.tolist()
​
# 条形图
bar1 = Bar(init_opts=opts.InitOpts(width='1350px', height='750px'))
bar1.add_xaxis(x_data)
bar1.add_yaxis('', y_data)
bar1.set_global_opts(title_opts=opts.TitleOpts(title='北京不同区域的二手房房源数量'),
                     visualmap_opts=opts.VisualMapOpts(max_=25648))
bar1.render('./html/北京不同区域的二手房房源数量.html')


'C:\\Users\\wzd\\Desktop\\CDA\\CDA_Python\\Python项目实作\\房价分析\\链家网\\code\\html\\北京不同区域的二手房房源数量.html'
北京不同区域的二手房均价

# 产生数据
s_region = df_all.groupby('region_name')['unitPrice'].mean().sort_values(ascending=False)
x_data = [i+'区' for i in s_region.index.tolist()]
y_data = [round(i) for i in s_region.values.tolist()]
​
data_pair = [list(z) for z in zip(x_data, y_data)]
​
# 地图
map1 = Map(init_opts=opts.InitOpts(width='1350px', height='750px'))
map1.add('', data_pair, maptype='北京')
map1.set_global_opts(title_opts=opts.TitleOpts(title='北京不同区域的二手房均价(元/平米)'),
                     visualmap_opts=opts.VisualMapOpts(max_=114979))
map1.render()
'C:\\Users\\wzd\\Desktop\\CDA\\CDA_Python\\Python项目实作\\房价分析\\链家网\\code\\render.html'
# 条形图
bar2 = Bar(init_opts=opts.InitOpts(width='1350px', height='750px'))
bar2.add_xaxis(x_data)
bar2.add_yaxis('', y_data)
bar2.set_global_opts(visualmap_opts=opts.VisualMapOpts(max_=114979))
bar2.render()
'C:\\Users\\wzd\\Desktop\\CDA\\CDA_Python\\Python项目实作\\房价分析\\链家网\\code\\render.html'
# 组合图
grid1 = Grid(init_opts=opts.InitOpts(width='1350px', height='750px'))
grid1.add(bar2, grid_opts=opts.GridOpts())
grid1.add(map1, grid_opts=opts.GridOpts(pos_left='70%', pos_right='20%',
                                        pos_top='5%', pos_bottom='30%')
         )
grid1.render()


'C:\\Users\\wzd\\Desktop\\CDA\\CDA_Python\\Python项目实作\\房价分析\\链家网\\code\\render.html'
客厅数量和房屋价格的关系

# 合并
df_all['halls'] = [i if i<=4 else '5及以上' for i in df_all['halls']]
df_all['halls'] = df_all.halls.astype('str')
df_all.head()
total_price    unitPrice    region_name    halls    bedrooms    area    orient    decorate_type    built_year    banta    subway    floor_type    price_cut
0    645    104810    东城    2    1    61.54    东    精装    10    板塔结合    0    中层    500-800万
1    564    97866    东城    2    1    57.63    东    精装    32    板楼    0    低层    500-800万
2    740    110448    东城    2    1    67.00    东    简装    17    板楼    1    高层    500-800万
3    635    103185    东城    2    1    61.54    东    精装    10    板塔结合    0    高层    500-800万
4    880    95694    东城    3    1    91.96    南    简装    17    板塔结合    0    中层    800-1000万
df_all.groupby('halls')['total_price'].describe()
count    mean    std    min    25%    50%    75%    max
halls                                
1    4624.0    379.452638    168.900504    74.0    255.0    338.0    470.0    1800.0
2    15500.0    469.239032    237.227545    96.0    305.0    405.0    575.0    3250.0
3    9696.0    694.628300    394.057674    115.0    430.0    580.0    855.0    5800.0
4    1857.0    1133.273560    759.608903    190.0    620.0    880.0    1390.0    6368.0
5及以上    771.0    1398.430610    960.443836    189.0    770.0    1140.0    1689.0    8299.0
# 添加数据
y1 = df_all[df_all['halls']=='1']['total_price'].values
y2 = df_all[df_all['halls']=='2']['total_price'].values
y3 = df_all[df_all['halls']=='3']['total_price'].values
y4 = df_all[df_all['halls']=='4']['total_price'].values
y5 = df_all[df_all['halls']=='5及以上']['total_price'].values
​
# 实例Figure
fig = go.Figure()
​
# 添加轨迹
fig.add_trace(trace=go.Box(y=y1, name='1厅'))
fig.add_trace(trace=go.Box(y=y2, name='2厅'))
fig.add_trace(trace=go.Box(y=y3, name='3厅'))
fig.add_trace(trace=go.Box(y=y4, name='4厅'))
fig.add_trace(trace=go.Box(y=y5, name='5厅及以上'))
​
fig.update_layout(title='客厅数量和房屋价格的关系(万元)')
py.offline.plot(fig, filename='./html/客厅数量和房屋价格的关系.html')


'./html/客厅数量和房屋价格的关系.html'
卧室数量和房屋单价的关系

# 合并
df_all['bedrooms'] = [i if i<=3 else '4及以上' for i in df_all['bedrooms']]
df_all['bedrooms'] = df_all.bedrooms.astype('str')
df_all.head()
total_price    unitPrice    region_name    halls    bedrooms    area    orient    decorate_type    built_year    banta    subway    floor_type    price_cut
0    645    104810    东城    2    1    61.54    东    精装    10    板塔结合    0    中层    500-800万
1    564    97866    东城    2    1    57.63    东    精装    32    板楼    0    低层    500-800万
2    740    110448    东城    2    1    67.00    东    简装    17    板楼    1    高层    500-800万
3    635    103185    东城    2    1    61.54    东    精装    10    板塔结合    0    高层    500-800万
4    880    95694    东城    3    1    91.96    南    简装    17    板塔结合    0    中层    800-1000万
df_all.groupby('bedrooms')['total_price'].describe()
count    mean    std    min    25%    50%    75%    max
bedrooms                                
0    780.0    361.176923    209.435520    74.0    230.0    325.0    445.75    4090.0
1    23375.0    500.001711    278.047016    77.0    310.0    425.0    610.00    5199.0
2    7848.0    808.228084    584.150202    120.0    440.0    625.0    980.00    8299.0
3    412.0    1403.485437    996.424241    328.0    750.0    1100.0    1750.00    7800.0
4及以上    33.0    1670.333333    1088.625012    699.0    1080.0    1280.0    1880.00    6600.0
# 添加数据
y1 = df_all[df_all['bedrooms']=='0']['total_price'].values
y2 = df_all[df_all['bedrooms']=='1']['total_price'].values
y3 = df_all[df_all['bedrooms']=='2']['total_price'].values
y4 = df_all[df_all['bedrooms']=='3']['total_price'].values
y5 = df_all[df_all['bedrooms']=='4及以上']['total_price'].values
​
# 实例Figure
fig = go.Figure()
​
# 添加轨迹
fig.add_trace(trace=go.Box(y=y1, name='0室'))
fig.add_trace(trace=go.Box(y=y2, name='1室'))
fig.add_trace(trace=go.Box(y=y3, name='2室'))
fig.add_trace(trace=go.Box(y=y4, name='3室'))
fig.add_trace(trace=go.Box(y=y5, name='4室及以上'))
​
fig.update_layout(title='卧室数量和房屋价格的关系(万元)')
py.offline.plot(fig, filename='./html/卧室数量和房屋价格的关系.html')


'./html/卧室数量和房屋价格的关系.html'
房屋朝向和房屋单价的关系

df_all.groupby('orient')['unitPrice'].describe()


count    mean    std    min    25%    50%    75%    max
orient                                
东    5922.0    69901.771361    30352.287882    13954.0    45484.25    63834.5    90822.50    189620.0
北    896.0    68833.779018    31238.408272    11337.0    44758.00    60449.5    88884.00    184180.0
南    22380.0    57242.026095    28908.047693    10484.0    37721.75    46826.5    68936.75    190000.0
西    3250.0    69751.665538    28673.113202    19301.0    47806.00    64198.5    89265.50    189452.0

orient_num = df_all.orient.value_counts()
​
x_data = orient_num.index.tolist()
y_data = orient_num.values.tolist()
​
data_pair = [list(z) for z in zip(x_data, y_data)]
# 绘制饼图
pie1 = Pie(init_opts=opts.InitOpts(width='1350px', height='750px'))
pie1.add('', data_pair=data_pair, radius=['30%', '60%'])
pie1.set_global_opts(title_opts=opts.TitleOpts(title='不同朝向的房屋数量分布'),
                     legend_opts=opts.LegendOpts(orient='vertical', pos_top='15%', pos_left='2%'))
pie1.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}:{d}%"))
pie1.set_colors(['#1F77B4', '#2CA02C', '#D62728', '#946C8B'])
pie1.render('./html/不同朝向的房屋数量分布.html')


'C:\\Users\\wzd\\Desktop\\CDA\\CDA_Python\\Python项目实作\\房价分析\\链家网\\code\\html\\不同朝向的房屋数量分布.html'
装修类型和房屋单价的关系

df_all['decorate_type'] = df_all.decorate_type.str.strip()
df_all.head()


total_price    unitPrice    region_name    halls    bedrooms    area    orient    decorate_type    built_year    banta    subway    floor_type    price_cut
0    645    104810    东城    2    1    61.54    东    精装    10    板塔结合    0    中层    500-800万
1    564    97866    东城    2    1    57.63    东    精装    32    板楼    0    低层    500-800万
2    740    110448    东城    2    1    67.00    东    简装    17    板楼    1    高层    500-800万
3    635    103185    东城    2    1    61.54    东    精装    10    板塔结合    0    高层    500-800万
4    880    95694    东城    3    1    91.96    南    简装    17    板塔结合    0    中层    800-1000万

df_all.groupby('decorate_type')['unitPrice'].describe()


count    mean    std    min    25%    50%    75%    max
decorate_type                                
其他    2942.0    58443.928960    33081.796043    12418.0    36118.50    44670.5    74956.25    188973.0
毛坯    938.0    54717.487207    28523.065916    11674.0    36190.75    45338.0    67001.00    168976.0
简装    12560.0    60620.529538    29859.630093    10484.0    38612.00    50129.0    78295.75    190000.0
精装    16008.0    62390.174913    29065.335004    11337.0    40938.75    53469.0    78674.00    189452.0

# 添加数据
y1 = df_all[df_all['decorate_type']=='精装']['unitPrice'].values
y2 = df_all[df_all['decorate_type']=='简装']['unitPrice'].values
y3 = df_all[df_all['decorate_type']=='毛坯']['unitPrice'].values
y4 = df_all[df_all['decorate_type']=='其他']['unitPrice'].values
​
# 实例Figure
fig = go.Figure()
​
# 添加轨迹
fig.add_trace(trace=go.Box(y=y1, name='精装'))
fig.add_trace(trace=go.Box(y=y2, name='简装'))
fig.add_trace(trace=go.Box(y=y3, name='毛坯'))
fig.add_trace(trace=go.Box(y=y4, name='其他'))
​
fig.update_layout(title='装修类型和房屋单价的关系(元/平米)')
py.offline.plot(fig, filename='./html/装修类型和房屋单价的关系.html')


'./html/装修类型和房屋单价的关系.html'
板塔结构和房屋单价的关系

df_all.groupby('banta')['unitPrice'].describe()


count    mean    std    min    25%    50%    75%    max
banta                                
塔楼    5468.0    71793.712692    28269.231504    16452.0    50057.00    66499.0    89014.25    186949.0
平房    14.0    87586.571429    41416.961530    35625.0    53580.25    82082.5    104806.75    160766.0
暂无数据    737.0    44731.162822    21014.903280    11337.0    30229.00    38837.0    52904.00    190000.0
板塔结合    5336.0    65976.914543    28156.005776    15918.0    44565.25    57867.0    84190.00    189452.0
板楼    20893.0    57655.142727    29867.069010    10484.0    37361.00    46330.0    70554.00    189962.0

banta_num = df_all.banta.value_counts()
​
data_pair = [list(z) for z in zip(banta_num.index.tolist(), banta_num.values.tolist())]
data_pair


[['板楼', 20893], ['塔楼', 5468], ['板塔结合', 5336], ['暂无数据', 737], ['平房', 14]]

# 绘制饼图
pie2 = Pie(init_opts=opts.InitOpts(width='1350px', height='750px'))
pie2.add('', data_pair=data_pair, radius=['30%', '60%'])
pie2.set_global_opts(title_opts=opts.TitleOpts(title='不同房屋结构的数量分布'),
                     legend_opts=opts.LegendOpts(orient='vertical', pos_top='15%', pos_left='2%'))
pie2.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}:{d}%"))
# pie2.set_colors(['#1F77B4', '#2CA02C', '#D62728', '#946C8B'])
pie2.render('./html/不同房屋结构的数量分布.html')


'C:\\Users\\wzd\\Desktop\\CDA\\CDA_Python\\Python项目实作\\房价分析\\链家网\\code\\html\\不同房屋结构的数量分布.html'
是否靠近地铁和房屋单价的关系

df_all.groupby('subway')['unitPrice'].describe()


count    mean    std    min    25%    50%    75%    max
subway                                
0    22115.0    58016.262175    29632.118847    10484.0    37165.0    47410.0    72353.0    189962.0
1    10333.0    67780.235653    29019.249541    16452.0    45074.0    59727.0    86478.0    190000.0

# 添加数据
y1 = df_all[df_all['subway']==1]['unitPrice'].values
y2 = df_all[df_all['subway']==0]['unitPrice'].values
​
# 实例Figure
fig = go.Figure()
​
# 添加轨迹
fig.add_trace(trace=go.Box(y=y1, name='靠近地铁'))
fig.add_trace(trace=go.Box(y=y2, name='不靠近地铁'))
​
fig.update_layout(title='是否靠近地铁和房屋单价的关系(元/平米)')
py.offline.plot(fig, filename='./html/是否靠近地铁和房屋单价的关系.html')


'./html/是否靠近地铁和房屋单价的关系.html'
房屋楼层和房屋价格的关系

df_all.groupby('floor_type')['unitPrice'].describe()


count    mean    std    min    25%    50%    75%    max
floor_type                                
中层    10941.0    62030.898638    29992.266364    13803.0    40051.0    51460.0    78617.0    189932.0
低层    9878.0    62189.100729    29598.212273    13954.0    40360.0    52360.0    79275.5    190000.0
地下室    170.0    69441.423529    30985.510824    11337.0    45782.0    70785.0    94448.5    139764.0
高层    11459.0    59221.029060    29631.162576    10484.0    37690.5    49004.0    75339.5    189757.0
房屋面积和房屋价格的关系

plt.scatter(x=df_all.area, y=df_all.total_price);

df_all[['area', 'total_price']] [点击并拖拽以移动] .corr()


area    total_price
area    1.000000    0.669298
total_price    0.669298    1.000000

# 添加轨迹
fig = px.scatter(df_all, x='area', y='total_price')
​
fig.update_layout(title='房屋面积和房屋价格的关系(万元)')
py.offline.plot(fig, filename='./html/房屋面积和房屋价格的关系.html')


'./html/房屋面积和房屋价格的关系.html'
房屋年龄和房屋单价的关系
 

​bins_built = [0, 5, 10, 15, 20, 71]
bins_label = ['5年以内', '5至10年', '10至15年', '15至20年', '20年以上']
df_all['built_cut'] = pd.cut(df_all['built_year'], bins=bins_built, right=True, labels=bins_label)
df_all.head()


total_price    unitPrice    region_name    halls    bedrooms    area    orient    decorate_type    built_year    banta    subway    floor_type    price_cut    built_cut
0    645    104810    东城    2    1    61.54    东    精装    10    板塔结合    0    中层    500-800万    5至10年
1    564    97866    东城    2    1    57.63    东    精装    32    板楼    0    低层    500-800万    20年以上
2    740    110448    东城    2    1    67.00    东    简装    17    板楼    1    高层    500-800万    15至20年
3    635    103185    东城    2    1    61.54    东    精装    10    板塔结合    0    高层    500-800万    5至10年
4    880    95694    东城    3    1    91.96    南    简装    17    板塔结合    0    中层    800-1000万    15至20年

built_num = df_all.built_cut.value_counts()


data_pair = [list(z) for z in zip(built_num.index, built_num.values.tolist())]
data_pair


[['20年以上', 10946],
 ['15至20年', 7835],
 ['10至15年', 6605],
 ['5至10年', 5620],
 ['5年以内', 1441]]

# 绘制饼图
pie3 = Pie(init_opts=opts.InitOpts(width='1350px', height='750px'))
pie3.add('', data_pair=data_pair, radius=['35%', '60%'])
pie3.set_global_opts(title_opts=opts.TitleOpts(title='北京二手房房龄分布'),
                     legend_opts=opts.LegendOpts(orient='vertical', pos_top='15%', pos_left='2%'))
pie3.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}:{c}套\n{d}%"))
pie3.set_colors(['#FF7F0E', '#1F77B4', '#2CA02C', '#D62728', '#946C8B'])
pie3.render('./html/北京二手房房龄分布.html')


'C:\\Users\\wzd\\Desktop\\CDA\\CDA_Python\\Python项目实作\\房价分析\\链家网\\code\\html\\北京二手房房龄分布.html'

df_all.groupby('built_cut')['unitPrice'].describe()


count    mean    std    min    25%    50%    75%    max
built_cut                                
5年以内    1441.0    48131.437196    21314.961648    13954.0    36207.00    44418.0    54740.00    184936.0
5至10年    5620.0    49352.455160    19653.139492    11337.0    37337.00    44115.5    55849.25    186493.0
10至15年    6605.0    58119.461317    25168.488035    13051.0    40565.00    51025.0    71017.00    189452.0
15至20年    7835.0    60056.471474    29769.246329    10484.0    38137.50    49614.0    78377.00    189101.0
20年以上    10946.0    71448.302394    33882.711018    16594.0    42250.25    63271.5    95433.25    189962.0
变量间的关系探索

分类:

不同区域和房屋价格的关系
客厅数量和房屋价格的关系
卧室数量和房屋价格的关系
房屋朝向和房屋价格的关系
装修类型和房屋价格的关系
板塔结构和房屋价格的关系
是否靠近地铁和房屋价格的关系
房屋楼层和房屋价格的关系
建筑年份(分箱)和房屋价格的关系
数值: 10. 房屋面积和房屋价格的关系

数据建模
假设预测房屋总价

# 去掉地下室的房子
df_sel = df_all[df_all.floor_type!='地下室']
df_sel.head()


total_price    unitPrice    region_name    halls    bedrooms    area    orient    decorate_type    built_year    banta    subway    floor_type    price_cut    built_cut
0    645    104810    东城    2    1    61.54    东    精装    10    板塔结合    0    中层    500-800万    5至10年
1    564    97866    东城    2    1    57.63    东    精装    32    板楼    0    低层    500-800万    20年以上
2    740    110448    东城    2    1    67.00    东    简装    17    板楼    1    高层    500-800万    15至20年
3    635    103185    东城    2    1    61.54    东    精装    10    板塔结合    0    高层    500-800万    5至10年
4    880    95694    东城    3    1    91.96    南    简装    17    板塔结合    0    中层    800-1000万    15至20年

# 选取字段
df_model = df_sel[['total_price', 'area', 'halls', 'bedrooms', 'subway', 'floor_type']].copy()
df_model.head()


total_price    area    halls    bedrooms    subway    floor_type
0    645    61.54    2    1    0    中层
1    564    57.63    2    1    0    低层
2    740    67.00    2    1    1    高层
3    635    61.54    2    1    0    高层
4    880    91.96    3    1    0    中层

# 转换类型
df_model['halls'] = df_model.halls.astype('str')
df_model['bedrooms'] = df_model.bedrooms.astype('str')
df_model['subway'] = df_model.subway.astype('str')
df_model.info()


<class 'pandas.core.frame.DataFrame'>
Int64Index: 32278 entries, 0 to 33569
Data columns (total 6 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   total_price  32278 non-null  int32  
 1   area         32278 non-null  float64
 2   halls        32278 non-null  object
 3   bedrooms     32278 non-null  object
 4   subway       32278 non-null  object
 5   floor_type   32278 non-null  object
dtypes: float64(1), int32(1), object(4)
memory usage: 1.6+ MB

df_model = pd.get_dummies(df_model)
df_model.head()


total_price    area    halls_1    halls_2    halls_3    halls_4    halls_5及以上    bedrooms_0    bedrooms_1    bedrooms_2    bedrooms_3    bedrooms_4及以上    subway_0    subway_1    floor_type_中层    floor_type_低层    floor_type_高层
0    645    61.54    0    1    0    0    0    0    1    0    0    0    1    0    1    0    0
1    564    57.63    0    1    0    0    0    0    1    0    0    0    1    0    0    1    0
2    740    67.00    0    1    0    0    0    0    1    0    0    0    0    1    0    0    1
3    635    61.54    0    1    0    0    0    0    1    0    0    0    1    0    0    0    1
4    880    91.96    0    0    1    0    0    0    1    0    0    0    1    0    1    0    0

二手房数据分析data.zip 预览 下载
发表回复
你还没有登录,请先 登录或 注册!