数据科学 4、描述性统计与探索型数据分析(代码)


供自己与新手学习!资源来自网络。
本文用到的数据集: 请点击 提取码:wyez

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
import os
get_ipython().magic('matplotlib inline')
# os.chdir(r'.\data')
snd = pd.read_csv(r'.\data\sndHsPr.csv')
snd.head()
distroomnumhallsAREAfloorsubwayschoolprice
0chaoyang1046.06middle1048850
1chaoyang1159.09middle1046540
2haidian52278.95high1171662
3haidian32207.00high1157972
4fengtai2153.32low1171268

数据预处理

1、根据单价和面积计算房屋价格(价格=单价×面积)

snd["all_pr2"]=snd[["price","AREA"]].apply(lambda x:x[0]*x[1], axis = 1 )
snd.head()
distroomnumhallsAREAfloorsubwayschoolpriceall_pr2
0chaoyang1046.06middle10488502250031.00
1chaoyang1159.09middle10465402750048.60
2haidian52278.95high117166219990114.90
3haidian32207.00high115797212000204.00
4fengtai2153.32low11712683800009.76

2、dist变量重新编码为中文,比如chaoyang改为朝阳区

1、把dist变量重新编码为中文,比如chaoyang改为朝阳区。1)先作频次统计,然后绘制柱形图图展现每个区样本的数量;

district = {'fengtai':'丰台区','haidian':'海淀区','chaoyang':'朝阳区','dongcheng':'东城区','xicheng':'西城区','shijingshan':'石景山区'}
snd['district'] = snd.dist.map(district)
# snd_new = snd.drop('dist',axis = 1)
snd.head()
distroomnumhallsAREAfloorsubwayschoolpriceall_pr2district
0chaoyang1046.06middle10488502250031.00朝阳区
1chaoyang1159.09middle10465402750048.60朝阳区
2haidian52278.95high117166219990114.90海淀区
3haidian32207.00high115797212000204.00海淀区
4fengtai2153.32low11712683800009.76丰台区

3、单因子频数:描述名义变量的分布

3.1统计名义变量的频数
#snd.dist.value_counts()
snd.district.value_counts()
# type(snd.district.value_counts())
# snd.district.value_counts()/snd.district.count()
# snd.district.count()
丰台区     2947
海淀区     2919
朝阳区     2864
东城区     2783
西城区     2750
石景山区    1947
Name: district, dtype: int64
3.2地区分布条形图与饼状图
  • 如遇中文显示问题可加入以下代码
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
# snd.district.value_counts().plot(kind = 'bar')
snd.district.value_counts().plot(kind = 'pie')  

在这里插入图片描述

4、单变量描述:描述连续变量的分布

4.1 平均值、中位数、标准差、倾斜
snd.price.mean()
snd.price.median()
snd.price.std()
snd.price.skew() #大于1表示右偏严重
0.6794935869486859
4.2 聚合函数:agg同时统计多个统计量:平均值、中位数、标准差、倾斜
snd.price.agg(['mean','median','sum','std','skew'])
mean      6.115181e+04
median    5.747300e+04
sum       9.912709e+08
std       2.229336e+04
skew      6.794936e-01
Name: price, dtype: float64
4.3 数据清洗函数quantile统计在1%、50%、99%的数据
  • 数据清洗:方便剔除异常值
snd.price.quantile([0.01,0.5,0.99])
0.01     27104.45
0.50     57473.00
0.99    119996.85
Name: price, dtype: float64
4.4绘制直方图(连续变量)
snd.price.hist(bins=40)

在这里插入图片描述

描述统计方法大全

1.1 crosstab函数(行,列)
sub_sch = pd.crosstab(snd.district,snd.school)
sub_sch
school01
district
东城区15081275
丰台区285394
朝阳区2267597
海淀区15331386
石景山区192918
西城区12071543
1.2分类柱形图
pd.crosstab(snd.dist,snd.subway).plot(kind="bar")

在这里插入图片描述

1.3 普通堆叠柱形图
#pd.crosstab(snd.district,snd.school).plot(kind = 'bar')
t1=pd.crosstab(snd.district,snd.school)
t1.plot(kind = 'bar',stacked= True)
type(t1)

在这里插入图片描述

1.4 标准化的堆叠柱形图

列的汇总

sub_sch = pd.crosstab(snd.district,snd.school)
sub_sch["sum1"]=sub_sch.sum(1)
sub_sch.head()
school01sum1
district
东城区150812752783
丰台区2853942947
朝阳区22675972864
海淀区153313862919
石景山区1929181947

按行求百分比

sub_sch = sub_sch.div(sub_sch.sum1,axis = 0)#每行除以该行的sum1值
sub_sch
school01sum1
district
东城区0.5418610.4581391.0
丰台区0.9681030.0318971.0
朝阳区0.7915500.2084501.0
海淀区0.5251800.4748201.0
石景山区0.9907550.0092451.0
西城区0.4389090.5610911.0
sub_sch[[0,1]].plot(kind = 'bar',stacked= True)

在这里插入图片描述

1.5 堆叠柱形图函数stack2dim
  • 能通过柱形图的粗细来反映数据量的多少
from stack2dim import *

stack2dim(snd, i="district", j="school")

在这里插入图片描述

1.6 地图绘制
# from pyecharts import Map #python3用不了
from pyecharts import options as opts
from pyecharts.charts import Map, Page
from pyecharts.faker import Collector, Faker
#from echarts-china-cities-pypkg import *
C = Collector()

"""
官网给的解释如下:

自从 0.3.2 开始,为了缩减项目本身的体积以及维持 pyecharts 项目的轻量化运行,pyecharts 将不再自带地图 js 文件。如用户需要用到地图图表,可自行安装对应的地图文件包。下面介绍如何安装。

全球国家地图: echarts-countries-pypkg (1.9MB): 世界地图和 213 个国家,包括中国地图
中国省级地图: echarts-china-provinces-pypkg (730KB):23 个省,5 个自治区
中国市级地图: echarts-china-cities-pypkg (3.8MB):370 个中国城市:https://github.com/echarts-maps/echarts-china-cities-js
pip install echarts-countries-pypkg
pip install echarts-china-provinces-pypkg
pip install echarts-china-cities-pypkg
别注明,中国地图在 echarts-countries-pypkg 里。
"""
#%%
snd_price = list(zip(snd.price.groupby(snd.district).mean().index,
                  snd.price.groupby(snd.district).mean().values))
min_ = snd.price.groupby(snd.dist).mean().min()
max_ = snd.price.groupby(snd.dist).mean().max()
@C.funcs
def map_visualmap() -> Map:
    c = (
        Map()
        .add("北京各区房价", [list(z) for z in zip(list(snd.price.groupby(snd.district).mean().index), list(snd.price.groupby(snd.district).mean().values))], "北京")
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Map-VisualMap(连续型)"),
            visualmap_opts=opts.VisualMapOpts(max_=max_,min_=min_),
        )
    )
    return c
Page().add(*[fn() for fn, _ in C.charts]).render()
'J:\\myGitHub\\Machine_Learning\\练习\\数据科学\\render.html'

在这里插入图片描述

1.7 条形图
snd.price.groupby(snd.district).mean().plot(kind="bar")

在这里插入图片描述

1.8 条形图排序
snd.price.groupby(snd.district).mean().sort_values(ascending= True).plot(kind = 'barh')

在这里插入图片描述

1.9 盒须图
  • x:离散变量(用来分组)
  • y:连续变量
sns.boxplot(x = 'district', y = 'price', data = snd)

在这里插入图片描述

1.10 汇总表
  • 地区:离散变量
  • 学校:离散变量
  • 价格:连续变量
snd.pivot_table(values='price', index='district', columns='school', aggfunc=np.mean)
school01
district
东城区66276.88793178514.900392
丰台区42291.00350548871.617021
朝阳区51588.51168957403.405360
海淀区61385.80365376911.258297
石景山区40353.88387833107.333333
西城区76989.36951192468.873623
snd.pivot_table(values='price', index='district', columns='school', aggfunc=np.mean).plot(kind = 'bar')

在这里插入图片描述

1.11 散点图(两个连续变量)
  • 使用area和price做散点图,分析area是否影响单位面积房价
snd.plot.scatter(x = 'AREA', y = 'price')

在这里插入图片描述

1.12 双轴图
  • 按年度汇总GDP,并计算GDP增长率。绘制双轴图。GDP为柱子,GDP增长率为线。
gdp = pd.read_csv('.\data\gdp_gdpcr.csv',encoding = 'gbk')
gdp.head()
yearGDPGDPCR
02000100280.18.5
12001110863.18.3
22002121717.49.1
32003137422.010.0
42004161840.210.1
x = list(gdp.year)
GDP = list(gdp.GDP)
GDPCR = list(gdp.GDPCR) #增长率
fig = plt.figure()
#左边的轴为主轴
ax1 = fig.add_subplot(111)
ax1.bar(x,GDP)
ax1.set_ylabel('GDP')
ax1.set_title("GDP of China(2000-2017)")
ax1.set_xlim(2000,2017)

#副轴通过镜像
ax2 = ax1.twinx()
ax2.plot(x,GDPCR,'r')
ax2.set_ylabel('Increase Ratio')
ax2.set_xlabel('Year')
Text(0.5, 0, 'Year')

在这里插入图片描述

1.13 logit图
  • 对age按照5岁间隔分段,命名为age_group,用loss_flag对age_group作logit图。
auto = pd.read_csv(r'.\data\auto_ins.csv',encoding = 'gbk')
auto
EngSizeAgeGenderMaritalexpOwnervAgeGarageAntiTFDimportLoss
02.056已婚20公司10有防盗装置进口0.0
11.841已婚20公司9无防盗装置国产0.0
22.044未婚20公司8有防盗装置国产0.0
31.656已婚20公司7有防盗装置国产0.0
41.845已婚20公司7无防盗装置国产0.0
....................................
42281.822未婚0私人1有防盗装置国产976.0
42292.522未婚0私人1无防盗装置进口855.6
42301.821未婚0私人1无防盗装置国产0.0
42311.821未婚0私人1无防盗装置进口3328.0
42322.421未婚0私人1无防盗装置进口1564.0

4233 rows × 11 columns

auto.Loss = auto.Loss.map(lambda x: 1 if x >0 else 0)
auto
EngSizeAgeGenderMaritalexpOwnervAgeGarageAntiTFDimportLoss
02.056已婚20公司10有防盗装置进口0
11.841已婚20公司9无防盗装置国产0
22.044未婚20公司8有防盗装置国产0
31.656已婚20公司7有防盗装置国产0
41.845已婚20公司7无防盗装置国产0
....................................
42281.822未婚0私人1有防盗装置国产1
42292.522未婚0私人1无防盗装置进口1
42301.821未婚0私人1无防盗装置国产0
42311.821未婚0私人1无防盗装置进口1
42322.421未婚0私人1无防盗装置进口1

4233 rows × 11 columns

#把年龄分段,并编号
bins = [21,26,31,36,41,46,51,56,61,67] #最大年龄:66,最小年龄:21
labels = [1,2,3,4,5,6,7,8,9]
auto['age_group'] = pd.cut(auto.Age, bins, labels = labels, right =False)
auto.head()
EngSizeAgeGenderMaritalexpOwnervAgeGarageAntiTFDimportLossage_group
02.056已婚20公司10有防盗装置进口08
11.841已婚20公司9无防盗装置国产05
22.044未婚20公司8有防盗装置国产05
31.656已婚20公司7有防盗装置国产08
41.845已婚20公司7无防盗装置国产05
log_tab = pd.crosstab(auto.age_group,auto.Loss)
log_tab
Loss01
age_group
18749
2308135
3743292
4826329
5578206
6324129
711241
84216
988
log_tab[['p0','p1']] = log_tab[[0,1]].apply(lambda x: x/sum(x))
log_tab['log'] = log_tab[['p1','p0']].apply(lambda x: np.log(x[0]/x[-1]),axis = 1)
log_tab
Loss01p0p1log
age_group
187490.0287320.0406640.347335
23081350.1017170.1120330.096598
37432920.2453760.242324-0.012519
48263290.2727870.2730290.000886
55782060.1908850.170954-0.110275
63241290.1070010.1070540.000492
7112410.0369880.034025-0.083504
842160.0138710.013278-0.043658
9880.0026420.0066390.921423

可以看出上面计算的是什么

log_tab.p0.sum(),log_tab.p1.sum(),np.log(log_tab.p1/log_tab.p0)
(0.9999999999999999, 1.0, age_group
 1    0.347335
 2    0.096598
 3   -0.012519
 4    0.000886
 5   -0.110275
 6    0.000492
 7   -0.083504
 8   -0.043658
 9    0.921423
 dtype: float64)
log_tab.log.plot()
from woe import WoE
# %matplotlib
woe = WoE(v_type='d')
woe.fit(auto.age_group,auto.Loss)
fig = woe.plot([8,5])  #[8,5]表示图的长宽
plt.show(fig)

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

irober

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值