• Python房价分析和可视化<房天下二手房>


    Python房价分析和可视化<房天下二手房>

    本文是Python数据分析实战的房价分析系列,本文分析二线城市贵阳的二手房。
    数据获取
    本文的数据来源于2022年8月房天下的二手房数据。对数据获取不感兴趣可以跳过此部分看分析和可视化。
    1.访问目标页面
    进入网站首页,点击选择城市和二手房进入<二手房信息页面>,筛选条件(位置、价格等)都保持默认,这样可以查出全部二手房信息。
    在这里插入图片描述2.分析url变化
    拖动滚动条到翻页的地方,点击几次<上一页>、<下一页>翻页,观察浏览器上方搜索框里url的变化。可以看到每次翻页url只变化一个数字,对应当前的页数。
    所以只要不断改变url中的页数,就可以获取所有的数据。
    3.二手房总数分析
    二手房信息很多,已经超过了网站的最大显示数量,房天下最多展示100页二手房数据,所以我们要获取的数据总页数为100。每页的信息是60条,按计算可以获取到6000条信息,但有些页面的数据没有获取完整,最后共获取到了3000多条信息(这个问题暂时不影响我的分析,有空再分析原因)。
    4.循环拼接url获取所有数据
    在url中从1开始拼接页数,直到第100页,依次获取所有页面的信息。
    参考代码:

    import time
    
    for p in range(1, 101):
        time.sleep(5)
        second_house_url = 'https://gy.esf.fang.com/house/i3{}'.format(p)
        try:
            res = requests.get(second_house_url, headers=headers)  # headers需要自己准备
            print('获取第{}页数据成功'.format(p))  
        except Exception as e:
            print('获取第{}页数据失败,报错:{}'.format(p, e))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    5.用XPath提取数据
    二手房信息在返回结果的HTML文件中,需要使用XPath语法提取。
    参考代码:

    from lxml import etree
    
    result = res.text
    html = etree.HTML(result)
    infos = html.xpath('//dl[@dataflag="bg"]')
    
    • 1
    • 2
    • 3
    • 4
    • 5

    XPath快速入门参考:快速入门XPath语法,轻松解析爬虫时的HTML内容
    用XPath获取当前页的所有二手房信息保存在infos中,infos是一个Element对象的列表,每一个Element对象里的信息是一条二手房信息,可以继续用XPath从中提取具体的信息。
    6.将数据保存到excel中
    使用pandas将解析的数据转换成DataFrame,然后保存到excel中。最终获取到的数据共3360条。
    在这里插入图片描述
    数据清洗
    1.删除重复值

    import pandas as pd
    import numpy as np
    
    df = pd.read_excel('fangtianxia_second_house.xlsx', index_col=False)
    print(df.shape)
    # 删除重复值
    df.drop_duplicates('标题', inplace=True)
    print(df.shape)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    (3360, 12)
    (2616, 12)
    
    • 1
    • 2

    删除重复值后,剩下的二手房信息为2616条,重复值很多,有700多条。
    2.填充空值

    # 空值填充
    print(np.any(df.isnull()))
    df.fillna('未知', inplace=True)
    print(np.any(df.isnull()))
    
    • 1
    • 2
    • 3
    • 4
    True
    False
    
    • 1
    • 2

    数据准备好后,本文开始对获取的2616条二手房信息进行分析。
    二手房所属楼盘Top30

    from pyecharts.charts import Bar
    from pyecharts import options as opts
    
    # 二手房数量Top30的楼盘
    second_build_name = df['楼盘'].value_counts()[0:30]
    bar = Bar(init_opts=opts.InitOpts(width='1000px', height='400px', bg_color='white'))
    bar.add_xaxis(
        second_build_name.index.to_list()
    ).add_yaxis(
        '', second_build_name.to_list(), category_gap='30%'
    ).set_global_opts(
        title_opts=opts.TitleOpts(title='二手房数量前30的楼盘', pos_left='400', pos_top='30',
            title_textstyle_opts=opts.TextStyleOpts(color='black', font_size=16)),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=10, distance=0, rotate=30, color='#4863C4'))
    ).set_colors('#4863C4').render('second_build_name_top30.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在这里插入图片描述在二手房的所属楼盘中,最多的两个楼盘是未来方舟和中铁逸都国际,都超过了100套二手房。
    二手房的单价分布

    from pyecharts.charts import Pie
    from pyecharts import options as opts
    
    # 获取各个价格区间的二手房数量
    second_price_unit = df['单价']
    sections = [0, 5000, 6000, 7000, 8000, 9000, 10000, 12000, 15000, 20000, 100000]
    group_names = ['less-5k', '5k-6k', '6k-7k', '7k-8k', '8k-9k', '9k-1w', '1w-1w2', '1w2-1w5', '1w5-2w', 'surpass-2w']
    cuts = pd.cut(np.array(second_price_unit), sections, labels=group_names)
    second_counts = pd.value_counts(cuts, sort=False)
    pie = Pie(init_opts=opts.InitOpts(width='800px', height='600px', bg_color='white'))
    pie.add(
        '', [list(z) for z in zip([gen for gen in second_counts.index], second_counts)],
        radius=['20%', '70%'], rosetype="radius", center=['60%', '50%']
    ).set_series_opts(
        label_opts=opts.LabelOpts(formatter="{b}: {c}"),
    ).set_global_opts(
        title_opts=opts.TitleOpts(title='二手房单价分布情况', pos_left='400', pos_top='30',
            title_textstyle_opts=opts.TextStyleOpts(color='black', font_size=16)),
        legend_opts=opts.LegendOpts(is_show=False)
    ).render('second_price_counts.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述从单价看,大部分二手房的单价在1w-1w5之间,如果按1000来切分最多的是7k-8k,不过7k-8k的数量明显比安居客的少了很多。
    对比安居客的二手房分析可以看历史文章:Python房价分析和可视化<anjuke贵阳二手房>
    二手房的总价分布

    from pyecharts.charts import Pie
    from pyecharts import options as opts
    
    # 获取二手房总价各区间的数量
    second_price_total = df['总价']
    sections = [0, 50, 60, 70, 80, 90, 100, 120, 150, 200, 250, 10000]
    group_names = ['less-50w', '50w-60w', '60w-70w', '70w-80w', '80w-90w', '90w-100w', '100w-120w', '120w-150w', '150w-200w', '200w-250w', 'surpass-250w']
    cuts = pd.cut(np.array(second_price_total), sections, labels=group_names)
    second_counts = pd.value_counts(cuts)
    pie = Pie(init_opts=opts.InitOpts(width='800px', height='600px', bg_color='white'))
    pie.add(
        '', [list(z) for z in zip([gen for gen in second_counts.index], second_counts)],
        radius=['20%', '70%'], rosetype="radius", center=['50%', '50%']
    ).set_series_opts(
        label_opts=opts.LabelOpts(formatter="{b}: {c}"),
    ).set_global_opts(
        title_opts=opts.TitleOpts(title='二手房总价分布情况', pos_left='330', pos_top='20',
            title_textstyle_opts=opts.TextStyleOpts(color='black', font_size=16)),
        legend_opts=opts.LegendOpts(is_show=False)
    ).set_colors(
        ['rgb(0,{g},{b})'.format(g=100+10*x, b=200-15*x) for x in range(12)]
    ).render('second_total_price_counts.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    在这里插入图片描述超过一半二手房的总价在100w之上,对比安居客的数据,安居客超过一半是90w之上,说明房天下平台上的二手房总价中位数比安居客上大约高了10w。
    二手房户型分布

    from pyecharts.charts import Bar
    from pyecharts import options as opts
    
    # 获取二手房的户型分布
    second_house_type = df['户型'].value_counts()
    unknown = second_house_type['未知']
    second_house_type.drop('未知', inplace=True)
    second_house_type_parse = second_house_type.loc[second_house_type >= 10]
    second_house_type_parse['others'] = second_house_type.loc[second_house_type < 10].sum()
    second_house_type_parse['未知'] = unknown
    bar = Bar(init_opts=opts.InitOpts(width='1000px', height='400px', bg_color='white'))
    bar.add_xaxis(
        second_house_type_parse.index.to_list()
    ).add_yaxis(
        '', second_house_type_parse.to_list(), category_gap='30%'
    ).set_global_opts(
        title_opts=opts.TitleOpts(title='二手房户型数量分布', pos_left='420', pos_top='30',
            title_textstyle_opts=opts.TextStyleOpts(color='black', font_size=16)),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=12, distance=0, rotate=20, color='#FF9366')),
        yaxis_opts=opts.AxisOpts(max_=1400)
    ).set_colors('#FF9366').render('second_house_type.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在这里插入图片描述大部分二手房的户型都是3室2厅,这与安居客上的分析结论一致。
    二手房面积分布

    from pyecharts.charts import Pie
    from pyecharts import options as opts
    
    # 获取二手房的面积分布情况
    df_second = df.drop(df.loc[df['面积']=='未知'].index)
    second_area = df_second['面积'].copy()
    print(second_area)
    sections = [0, 50, 80, 90, 100, 110, 120, 130, 140, 150, 200, 10000]
    group_names = ['0-50㎡', '50-80㎡', '80-90㎡', '90-100㎡', '100-110㎡', '110-120㎡', '120-130㎡', '130-140㎡', '140-150㎡', '150-200㎡', '200㎡以上']
    cuts = pd.cut(np.array(second_area), sections, labels=group_names)
    second_area_counts = pd.value_counts(cuts, ascending=True)
    pie = Pie(init_opts=opts.InitOpts(width='800px', height='600px', bg_color='white'))
    pie.add(
        '', [list(z) for z in zip([gen for gen in second_area_counts.index], second_area_counts)],
        radius=['20%', '70%'], rosetype="radius", center=['50%', '50%']
    ).set_series_opts(
        label_opts=opts.LabelOpts(formatter="{b}: {c}"),
    ).set_global_opts(
        title_opts=opts.TitleOpts(title='二手房面积分布情况', pos_left='330', pos_top='20',
            title_textstyle_opts=opts.TextStyleOpts(color='black', font_size=16)),
        legend_opts=opts.LegendOpts(is_show=False)
    ).set_colors(
        ['rgb({r},0,{b})'.format(r=20*x, b=250-15*x) for x in range(12)]
    ).render('second_area_counts.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在这里插入图片描述超过一半的二手房面积在110平到200平之间,安居客上的数据是120平到140平之间,这应该也是房天下平台的二手房总价更高的原因。
    二手房朝向分布

    from pyecharts.charts import Pie
    from pyecharts import options as opts
    import re
    
    # 处理部分错列的数据
    def toward_parse(toward):
        return '南向' if re.findall(r'(\d+).*', toward) else toward
    
    
    # 统计二手房的朝向
    df['朝向分布'] = df['朝向'].apply(toward_parse)
    second_house_toward = df['朝向分布'].value_counts()
    pie = Pie(init_opts=opts.InitOpts(width='800px', height='600px', bg_color='white'))
    pie.add(
        '', [list(z) for z in zip([gen for gen in second_house_toward.index], second_house_toward)],
        radius=['40%', '60%'], center=['50%', '50%']
    ).set_series_opts(
        label_opts=opts.LabelOpts(formatter="{b}: {c}"),
    ).set_global_opts(
        title_opts=opts.TitleOpts(title='二手房朝向分布情况', pos_left='330', pos_top='20',
            title_textstyle_opts=opts.TextStyleOpts(color='black', font_size=16)),
        legend_opts=opts.LegendOpts(is_show=False)
    ).render('second_house_toward.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    在这里插入图片描述南北朝向的二手房接近7成,加上东南和西南朝向,接近了9成,这与安居客的分析结论一致。
    二手房的修建年份

    from pyecharts.charts import Bar
    from pyecharts import options as opts
    
    # 获取二手房的修建年份
    second_house_build_year = df['年限'].copy().value_counts()
    unknown = second_house_build_year['未知']
    second_house_build_year.drop(['未知', '南向', '东向', '西向'], inplace=True)  # 处理部分错列的数据
    second_house_build_year.index = [y[0:4] for y in second_house_build_year.index.to_list()]
    second_house_build_year = second_house_build_year.sort_index(ascending=False)
    second_house_build_year['未知'] = unknown
    bar = Bar(init_opts=opts.InitOpts(width='1000px', height='400px', bg_color='white'))
    bar.add_xaxis([i for i in second_house_build_year.index]).add_yaxis(
        '', second_house_build_year.to_list(), category_gap='20%'
    ).set_series_opts(
        label_opts=opts.LabelOpts(font_size=12)
    ).set_global_opts(
        title_opts=opts.TitleOpts(title='二手房修建年份分布', pos_left='420', pos_top='20',
            title_textstyle_opts=opts.TextStyleOpts(color='black', font_size=16)),
        yaxis_opts=opts.AxisOpts(max_=400),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=10, rotate=30, interval=0, color='#4863C4'))
    ).set_colors(['#4863C4']).render('second_house_build_year.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在这里插入图片描述二手房的修建年份除了大部分在15年内,还有2000年也很多。
    二手房信息的标题风格

    import jieba
    from wordcloud import WordCloud
    from PIL import Image
    
    second_house_title = df['标题']
    title_content = ','.join([str(til.replace(' ', '')) for til in second_house_title.to_list()])
    cut_text = jieba.cut(title_content)
    result = ' '.join(cut_text)
    shape = np.array(Image.open("ciyun001.png"))
    wc = WordCloud(font_path="simhei.ttf", max_font_size=70, background_color='white', colormap='winter',
                   prefer_horizontal=1, mask=shape, relative_scaling=0.1)
    wc.generate(result)
    wc.to_file("second_house_title.png")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述
    在海量的二手房信息中,好标题可以吸引更多潜在买家点击,还有可能提高成交几率。在这2600多条二手房信息的标题中,高频出现的词主要有诚心出售、几室几厅、地铁口、精装修、带车位、带地暖等。
    对比安居客上的信息,诚心出售是房天下上的标题高频词,带车位、带地暖是更多人提到的卖点,而使用急售、南北通透、领包入住、随时看房的明显比安居客上少,整体来看,房天下上的标题起得比安居客上的更好。
    总结
    本文获取了房天下贵阳市的二手房数据,对数据进行各个维度的分析,并用Python进行可视化。
    从安居客和房天下的二手房信息分析结论来看,有一部分数据是两个平台重复的,但也有很大一部分只在其中一个平台有。
    文中用到的Python库和工具以后会专门写文章详细介绍,对代码有疑问可以关注和联系我一起交流讨论,欢迎点赞、评论和收藏。

  • 相关阅读:
    React中setState方法详细讲解
    UnitTest 参数化---Parameterized安装
    防脱发、再生发
    Spring AOP 源码 (二) (大致过程)
    为什么要学习Flink系统管理及优化课程?
    【第二章 数据的表示和运算】d1
    PyCharm中 python 类型文件被识别为Text文本类型
    自然语言处理学习笔记-lecture06-词法分析与词性标注
    vue2和vue3 的双向绑定原理
    shell命令合集(loading)
  • 原文地址:https://blog.csdn.net/weixin_43790276/article/details/126335181