发布于2020-03-25 09:30 阅读(1736) 评论(0) 点赞(3) 收藏(0)
数据探索性分析
Notes:
#导入warning包,利用过滤器来实现忽略警告语句
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import missingno as msno # 缺失值可视化处理
import plotly.express as px
import plotly.io as pio
pio.templates.default = 'plotly_white'
Notes:
path = '../data/'
Train_data = pd.read_csv(path + 'used_car_train_20200313.csv', sep=' ')
Test_data = pd.read_csv(path + 'used_car_testA_20200313.csv', sep = ' ')
Notes:
Train_data.head().append(Train_data.tail())
Train_data.shape
Test_data.head().append(Test_data.tail())
Test_data.shape()
Notes:
Train_data.describe()
Test_data.describe()
Notes
Train_data.info()
Test_data.info()
Train_data.isnull().sum()
Test_data.isnull().sum()
Notes:
msno.matrix(Train_data.sample(250)) # why need sample?
msno.bar(Train_data.sample(1000))
msno.heatmap(Train_data)
Train_data['notRepairedDamage'].value_counts() #‘ - ’也为空缺值
Train_data['notRepairedDamage'].replace('-',np.nan,inplace=True)
# 因为很多模型对nan有直接的处理,这里我们先不做处理,先替换成nan
Train_data['notRepairedDamage'].value_counts()
# 对Test data做同样的处理
Test_data['notRepairedDamage'].value_counts()
Test_data['notRepairedDamage'].replace('-',np.nan,inplace=True)
Notes:
Train_data["seller"].value_counts()
Train_data["offerType"].value_counts()
del Train_data["seller"]
del Train_data["offerType"]
del Test_data["seller"]
del Test_data["offerType"]
Notes:
import scipy.stats as st
y = Train_data['price']
plt.figure(1);plt.title('Johnson SU')
sns.distplot(y,kde=False,fit=st.johnsonsu) # kde=False关闭核密度分布,rug表示在x轴上每个观测上生成的小细条(边际毛毯)
sns.distplot(Train_data['price']) # 单个变量y
print("Skewness: %f" % Train_data['price'].skew())
print("Kurtosis: %f" % Train_data['price'].kurt())
查看所有变量
Train_data.skew(),Train_data.kurt()
# 偏度的频率图
sns.distplot(Train_data.skew(),color='blue',axlabel='Skewness')
sns.distplot(Train_data.kurt(),color = 'orange', axlabel = 'Kurtness')
Notes
plt.hist(Train_data['price'],orientation = 'vertical',histtype = 'bar', color = 'red')
plt.show()
Notes:
plt.hist(np.log(Train_data['price']),
orientation='vertical',
histtype = 'bar',
color = 'red')
plt.show()
for cat_fea in categorical_features:
print(cat_fea + "的特征分布如下")
print("{}的特征有{}个不同的值".format(cat_fea,Train_data[cat_fea].nunique()))
print(Train_data[cat_fea].value_counts())
numeric_features.append('price')
price_numeric = Train_data[numeric_features]
correlation = price_numeric.corr()
print(correlation['price'].sort_values(ascending = False),'\n')
Heatmap
f,ax = plt.subplots(figsize = (7,7))
plt.title('Correlation of Numeric Features with Price',y=1,size =16)
sns.heatmap(correlation,square = True,vmax = 0.8)
del price_numeric['price']
for col in numeric_features:
print('{:15}'.format(col),
'Skewness: {:05.2f}'.format(Train_data[col].skew()),
' ',
'Kurtosis: {:06.2f}'.format(Train_data[col].kurt()))
Notes:
f = pd.melt(Train_data,value_vars = numeric_features)
g = sns.FacetGrid(f,col="variable",col_wrap=2, sharex =False, sharey = False)
g = g.map(sns.distplot,"value")
Notes:
sns.set()
columns = ['price', 'v_12', 'v_8' , 'v_0', 'power', 'v_5', 'v_2', 'v_6', 'v_1', 'v_14']
sns.pairplot(Train_data[columns],size = 2,kind='scatter',diag_kind='kde')
plt.show()
fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6), (ax7, ax8), (ax9, ax10)) = plt.subplots(nrows=5, ncols=2, figsize=(24, 20))
v_12_scatter_plot = pd.concat([Y_train,Train_data['v_12']],axis=1)
sns.regplot(x='v_12',y='price',data = v_12_scatter_plot,scatter=True,fit_reg=True,ax=ax1)
v_8_scatter_plot = pd.concat([Y_train,Train_data['v_8']],axis = 1)
sns.regplot(x='v_8',y = 'price',data = v_8_scatter_plot,scatter= True, fit_reg=True, ax=ax2)
v_0_scatter_plot = pd.concat([Y_train,Train_data['v_0']],axis = 1)
sns.regplot(x='v_0',y = 'price',data = v_0_scatter_plot,scatter= True, fit_reg=True, ax=ax3)
power_scatter_plot = pd.concat([Y_train,Train_data['power']],axis = 1)
sns.regplot(x='power',y = 'price',data = power_scatter_plot,scatter= True, fit_reg=True, ax=ax4)
v_5_scatter_plot = pd.concat([Y_train,Train_data['v_5']],axis = 1)
sns.regplot(x='v_5',y = 'price',data = v_5_scatter_plot,scatter= True, fit_reg=True, ax=ax5)
v_2_scatter_plot = pd.concat([Y_train,Train_data['v_2']],axis = 1)
sns.regplot(x='v_2',y = 'price',data = v_2_scatter_plot,scatter= True, fit_reg=True, ax=ax6)
v_6_scatter_plot = pd.concat([Y_train,Train_data['v_6']],axis = 1)
sns.regplot(x='v_6',y = 'price',data = v_6_scatter_plot,scatter= True, fit_reg=True, ax=ax7)
v_1_scatter_plot = pd.concat([Y_train,Train_data['v_1']],axis = 1)
sns.regplot(x='v_1',y = 'price',data = v_1_scatter_plot,scatter= True, fit_reg=True, ax=ax8)
v_14_scatter_plot = pd.concat([Y_train,Train_data['v_14']],axis = 1)
sns.regplot(x='v_14',y = 'price',data = v_14_scatter_plot,scatter= True, fit_reg=True, ax=ax9)
v_13_scatter_plot = pd.concat([Y_train,Train_data['v_13']],axis = 1)
sns.regplot(x='v_13',y = 'price',data = v_13_scatter_plot,scatter= True, fit_reg=True, ax=ax10)
for fea in categorical_features:
print(Train_data[fea].nunique())
Notes:
categorical_features = ['model',
'brand',
'bodyType',
'fuelType',
'gearbox',
'notRepairedDamage']
for c in categorical_features:
Train_data[c] = Train_data[c].astype('category')
if Train_data[c].isnull().any():
Train_data[c] = Train_data[c].cat.add_categories(['MISSING'])
Train_data[c] = Train_data[c].fillna('MISSING')
def boxplot(x,y,**kwargs):
sns.boxplot(x=x, y=y)
x=plt.xticks(rotation=90)
f = pd.melt(Train_data,id_vars = ['price'],value_vars=categorical_features)
g = sns.FacetGrid(f,col="variable",col_wrap=2,sharex=False, sharey=False,size=5)
g = g.map(boxplot,"value","price")
Notes:
catg_list = categorical_features
target = 'price'
for catg in catg_list:
sns.violinplot(x=catg,y=target,data=Train_data)
plt.show()
Notes:
plt.style.use("ggplot")
def bar_plot(x,y,**kwargs):
sns.barplot(x=x,y=y)
x=plt.xticks(rotation = 90)
f = pd.melt(Train_data,id_vars=['price'],value_vars=categorical_features)
g = sns.FacetGrid(f,col="variable",col_wrap=2,sharex=False,sharey=False,size=5)
g = g.map(bar_plot,"value","price")
plt.style.use("ggplot")
def count_plot(x,**kwargs):
sns.countplot(x=x)
x=plt.xticks(rotation=90)
f = pd.melt(Train_data,value_vars=categorical_features)
g = sns.FacetGrid(f,col="variable",col_wrap=2,sharex=False,sharey=False,size=5)
g = g.map(count_plot,"value")
用pandas_profiling生成一个较为全面的可视化和数据报告(较为简单、方便) 最终打开html文件即可
import pandas_profiling
pfr = pandas_profiling.ProfileReport(Train_data)
pfr.to_file("./example.html")
原文链接:https://blog.csdn.net/qq_39481446/article/details/105056711
作者:dfd323
链接:https://www.pythonheidong.com/blog/article/281787/adb50a16c35faa7e8b35/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!