#!/usr/bin/env python
# coding: utf-8
# In[99]:
# coding:utf-8
# 【 项目:深圳市二手房房价分析及预测 】
# --------------------------------【 数据理解 】--------------------------------------
# (一) 导入数据 并进行初步的数据观察
# 1.改变工作目录到 数据集所在文件夹
import os
import pandas as pd
pd.set_option('display.max_columns', None)
data_path = r'D:\learning\project_data\Data_of_House_Price_ShenZhen'
save_path = r'D:\learning\project_data'
# 改变当前工作目录到指定的路径
os.chdir(data_path)
loadfile = os.listdir() # 读取目录下所有文件
df = pd.DataFrame()
for i in loadfile:
# locals() 没有返回局部名字空间,返回拷贝。修改的是拷贝,实际变量值无影响。
locals()[i.split('.')[0]] = pd.read_excel(i)
df = pd.concat([df, locals()[i.split('.')[0]]], ignore_index=True)
df = df.rename(columns={'Unnamed: 0': 'houseid'})
print('深圳各区二手房房价信息合并完成')
print('=' * 100)
print(df.head())
print(df.count())
# In[105]:
# 2.查看数据情况
# # 1) 数据总体情况
print('数据集中的样本量共有%d个' % df.shape[0]) # 行数
print(df.duplicated()) # 是否有重复
print(df.head())
print(df.describe(include='all').T) # 查看描述基本信息
del df['houseid']
del df['floor_num']
# df.drop_duplicates() 删除重复行
df['hall'] = df['hall'].astype('int64') # 改变数据类型
df.info() # 查看数据类型是否有误
# In[107]:
# # 2) 查看分类变量的取值
import sqlite3
con = sqlite3.connect(':memory:')
df.to_sql('df', con)
print(list(df))
print('查看分类变量的取值')
for i in list(df[['district', 'roomnum', 'hall', 'C_floor', 'school', 'subway']]):
s = pd.read_sql_query('SELECT DISTINCT %s from df' % i, con)
print(s)
print('-' * 12)
print('=' * 100)
# In[110]:
# # 3) 将城区名由拼音改成中文,方便之后作图时查看
dist_dict = {'longgang': '龙岗', 'longhua': '龙华', 'baoan': '宝安', 'nanshan': '南山', 'futian': '福田', 'luohu': '罗湖',
'pingshan': '坪山', 'guangming': '光明', 'yantian': '盐田'}
df['district'] = df['district'].apply(lambda x: dist_dict[x])
# # 3) 将楼层名变为英文,方便之后作图时查看
C_floor = {' 低层': 'low', ' 中层': 'middle', ' 高层': 'high'}
df['C_floor'] = df['C_floor'].apply(lambda x: C_floor[x])
print(df.head())
print('=' * 100)
# In[5]:
# # 4) 生成一个excel表格用于分析列名含义
table_columns = pd.DataFrame(columns=['表名', '表说明', '列名', '列名含义', '备注'])
table_columns['列名'] = list(df)
table_columns.to_excel(save_path + r'\列名含义分析表.xls')
print('列名含义分析表 已生成')
print('=' * 100) # 划分割线,方便查看
# In[112]:
# --------------------------------【 目标拆解分析 】--------------------------------------
# (二) 因变量分析
# # 1. 单位面积房价分析
# # # 设置负号显示及字体
from matplotlib import pylab
pylab.rcParams['font.sans-serif'] = ['SimHei']
pylab.rcParams['axes.unicode_minus'] = False
# # # 1) 作因变量直方图
import matplotlib.pyplot as plt
df.per_price.hist(grid=False, bins=20, color='lightblue')
plt.title('单位面积房价频数图')
plt.xlabel('单位面积房价(万元/平方米)')
plt.ylabel('频数')
plt.show()
'''
通过直方图可发现数据是偏态分布的(右偏 → 那么之后可能会取对数)
'''
# In[113]:
# # # 2) 查看 均值、中位数、标准差、四分位数
print(df.per_price.agg(['mean', 'median', 'std']))
print(df.per_price.quantile([0.25, 0.5, 0.75]))
# In[114]:
print('max:%s万元/㎡' % max(df.per_price))
print('min:%s万元/㎡' % min(df.per_price))
# In[125]:
# (三) 自变量
# # 1. 整体来看
# # # 1) 分类变量 看 各个取值 的 数量统计 情况
for i in range(len(list(df))):
if i != list(df).index('AREA') and i != list(df).index('per_price'):
print(df.columns.values[i], ':')
print(df[df.columns.values[i]].value_counts())
else:
continue
'''
dist列中 每个区的样本量均在300以上,该数据只爬取了每区前10页,所有样本量差不多;
roomnum列中 最多的类型是3房,6~9房的占比很少;
halls列中 最普遍的是2个;
floor列中 middle的数量多一些,high和low基本持平;
subway列中 有地铁多一点;
school列中 学区房更多一些
'''
# In[126]:
# # # 2) 连续变量 看 最小、最大值、平均数、中位数、标准差
print('AREA:')
print(df.AREA.agg(['min', 'mean', 'median', 'max', 'std']).T)
# In[127]:
# # 2. 分开各个量 → district列
# # # 各个区的房屋信息数量情况比较,饼图
colors = ['#71ae46', '#96b744', '#c4cc38', '#ebe12a', '#eab026', '#e3852b', '#d85d2a', '#ce2626', '#ac2026', '#71ae46']
df.district.value_counts().sort_values().plot(kind='pie', autopct="%1.1f%%", colors=colors)
plt.title('各个区的房屋数量情况比较')
plt.show()
print(df.district.value_counts().sort_values(ascending=False))
# In[128]:
# # # 各个区房价均值比较
colors = ['#71ae46', '#71ae46', '#96b744', '#c4cc38', '#ebe12a', '#eab026', '#e3852b', '#d85d2a', '#ce2626', '#ac2026']
df.per_price.groupby(df.district).mean().sort_values().plot(kind='barh', color=colors)
plt.xlabel('各个区房价均值(万元/平方米)')
plt.ylabel('区名')
plt.title('各个区的房价均值情况表')
A = df.per_price.groupby(df.district).mean().sort_values()
for i in range(len(list(df.district.value_counts()))):
plt.text(A[i], i, round(A[i], 4), fontsize=12, verticalalignment="center", horizontalalignment="right")
plt.show()
# In[129]:
# # # 不同城区的单位面积房价(箱线图)
import seaborn as sns
df_temp1 = df[['district', 'per_price']].sort_values(by=['district'])
df_temp1['district'] = df_temp1['district'].astype('category')
df_temp1['district'] = df_temp1['district'].cat.set_categories(['坪山', '龙岗', '光明', '盐田', '龙华', '罗湖', '宝安', '福田', '南山'])
plt.figure(figsize=(12, 6))
sns.boxplot(x='district', y='per_price', data=df_temp1, linewidth=0.5,
palette=sns.cubehelix_palette(16, start=2, rot=2, dark=0, light=.95))
plt.ylabel('单位面积房价(万元/㎡)')
plt.xlabel('城区')
plt.title('不同城区的单位面积房价的分组箱线图')
plt.show()
'''
由箱线图可知,随着x值的不同,中心水平是有变化的,故可初步判断二者是有关系的
'''
# In[131]:
# # 3. 分开各个量 → roomnum列
# # # 不同卧室数的单位面积房价
df.per_price.groupby(df.roomnum).mean().plot(kind='bar', color=colors)
plt.xticks(rotation=360)
plt.title('不同卧室数的单位面积房价-直方图')
plt.show()
df_temp2 = df[['roomnum', 'per_price']]
# df_temp2.boxplot(by='roomnum',patch_artist=True) # patch_artist上下四分位框内是否填充,True为填充
plt.figure(figsize=(12, 6))
sns.boxplot(x=df_temp2['roomnum'], y=df_temp2['per_price'],
palette=sns.cubehelix_palette(16, start=2, rot=0, dark=0, light=.95))
plt.title('不同卧室数的单位面积房价-箱线图')
plt.show()
'''
直方图中roomnum=9的房价较大,考虑到数量较少,个别情况影响比较大
'''
# In[133]:
# # 4. 分开各个量 → hall列
# # # 不同厅数的单位面积房价
df.per_price.groupby(df.hall).mean().plot(kind='bar', color=colors)
plt.xticks(rotation=360)
plt.title('不同厅数的单位面积房价-直方图')
plt.show()
df_temp3 = df[['hall', 'per_price']]
plt.figure(figsize=(10, 6))
sns.boxplot(x=df_temp3['hall'], y=df_temp3['per_price'],
palette=sns.cubehelix_palette(10, start=2, rot=0, dark=0, light=.95))
plt.title('不同厅数的单位面积房价-箱线图')
plt.show()
# In[134]:
# # 5. 分开各个量 → C_floor列
df_temp4 = df[['C_floor', 'per_price']]
sns.boxplot(x=df_temp4['C_floor'], y=df_temp4['per_price'],
palette=sns.cubehelix_palette
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
收起资源包目录
![package](https://csdnimg.cn/release/downloadcmsfe/public/img/package.f3fc750b.png)
![folder](https://csdnimg.cn/release/downloadcmsfe/public/img/folder.005fa2e5.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/PNG.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![folder](https://csdnimg.cn/release/downloadcmsfe/public/img/folder.005fa2e5.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/XLS.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/XLS.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/XLS.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/XLS.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/XLS.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/XLS.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/XLS.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/XLS.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/XLS.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
共 12 条
- 1
资源评论
![avatar-default](https://csdnimg.cn/release/downloadcmsfe/public/img/lazyLogo2.1882d7f4.png)
![avatar](https://profile-avatar.csdnimg.cn/d5b8e16cddf148da83293d5bb68d9224_admin_maxin.jpg!1)
博士僧小星
- 粉丝: 1947
- 资源: 5905
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助
![voice](https://csdnimg.cn/release/downloadcmsfe/public/img/voice.245cc511.png)
![center-task](https://csdnimg.cn/release/downloadcmsfe/public/img/center-task.c2eda91a.png)
安全验证
文档复制为VIP权益,开通VIP直接复制
![dialog-icon](https://csdnimg.cn/release/downloadcmsfe/public/img/green-success.6a4acb44.png)