債務(wù)違約預(yù)測之二:圖形探索

%matplotlib inline
import pandas as pd
import numpy as np 
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.gridspec as gridspec
pd.set_option("display.max_columns",101)
pd.set_option('display.float_format', lambda x: '%.5f' % x) #為了直觀的顯示數(shù)字,不采用科學(xué)計數(shù)法
pd.options.display.max_rows = 15 #最多顯示15行
import warnings
warnings.filterwarnings('ignore') #為了整潔,去除彈出的warnings
import pandas as pd

df=pd.read_csv( 'cs-training.csv')
df = df.drop(df.columns[0],axis=1)
df=df[df.age>=18]

債務(wù)違約預(yù)測之一:數(shù)據(jù)探索中,按各個屬性對借貸者分組,再分析其違約率?,F(xiàn)在換一個角度,分為違約者和未違約兩類,再查看兩組人群中各個屬性的分布。

features=df.columns[1:]
features
Index(['RevolvingUtilizationOfUnsecuredLines', 'age',
       'NumberOfTime30-59DaysPastDueNotWorse', 'DebtRatio', 'MonthlyIncome',
       'NumberOfOpenCreditLinesAndLoans', 'NumberOfTimes90DaysLate',
       'NumberRealEstateLoansOrLines', 'NumberOfTime60-89DaysPastDueNotWorse',
       'NumberOfDependents'],
      dtype='object')
plt.figure(figsize=(12,28*4))
gs = gridspec.GridSpec(28, 1)
#針對違約者和未違約者的每個屬性,繪制直方圖
for i, cn in enumerate(features):
    ax = plt.subplot(gs[i])
    sns.distplot(df[cn][df.SeriousDlqin2yrs == 1], bins=50,color='red')
    sns.distplot(df[cn][df.SeriousDlqin2yrs == 0], bins=50,color='blue')
    ax.set_xlabel('')
    ax.set_title('histogram of feature: ' + str(cn))
plt.show()

出現(xiàn) 'max must be larger than min in range parameter.'是因為有的列存在空值。

df.isnull().sum()

MonthlyIncome為空的記錄較多,為了保持?jǐn)?shù)據(jù)的完整,沒有刪掉,用平均值填充

df['MonthlyIncome'].fillna(df['MonthlyIncome'].mean(), inplace=True)
df['NumberOfDependents'].fillna(df['NumberOfDependents'].mode(), inplace=True)
#NumberOfDependents字段,用眾數(shù)df['NumberOfDependents'].mode()來填充
df.isnull().sum() #空值還是存在,為什么呢
SeriousDlqin2yrs                           0
RevolvingUtilizationOfUnsecuredLines       0
age                                        0
NumberOfTime30-59DaysPastDueNotWorse       0
DebtRatio                                  0
MonthlyIncome                              0
NumberOfOpenCreditLinesAndLoans            0
NumberOfTimes90DaysLate                    0
NumberRealEstateLoansOrLines               0
NumberOfTime60-89DaysPastDueNotWorse       0
NumberOfDependents                      3924
dtype: int64
type(df['NumberOfDependents'].mode()) 
    pandas.core.series.Series
 #mode()返回的是一個Series,而不是單一的值,要取其中的元素來填充
df['NumberOfDependents'].fillna(df['NumberOfDependents'].mode()[0], inplace=True)#填補(bǔ)成功
sns.distplot(df['RevolvingUtilizationOfUnsecuredLines'][(df.SeriousDlqin2yrs == 1) & (df.RevolvingUtilizationOfUnsecuredLines)], bins=20,color='red')
sns.distplot(df['RevolvingUtilizationOfUnsecuredLines'][(df.SeriousDlqin2yrs == 0) & (df.RevolvingUtilizationOfUnsecuredLines)], bins=20,color='blue')
<matplotlib.axes._subplots.AxesSubplot at 0x10229a58>
output_15_1.png

圖形縮成小小的一條,因為取值范圍是0到50000多,x軸的范圍太大了,而大部分值都在0附近,所以無法清晰顯示。

df['RevolvingUtilizationOfUnsecuredLines'].describe() #看該屬性的數(shù)值分布
count   149999.00000
mean         6.04847
std        249.75620
min          0.00000
25%          0.02987
50%          0.15418
75%          0.55904
max      50708.00000
Name: RevolvingUtilizationOfUnsecuredLines, dtype: float64
df[['RevolvingUtilizationOfUnsecuredLines']].boxplot(sym='r*') #用箱型圖查看異常值
<matplotlib.axes._subplots.AxesSubplot at 0x100f1828>
output_18_1.png
p=df[['RevolvingUtilizationOfUnsecuredLines']].boxplot(return_type='dict')
#return_type='dict'時,會返回數(shù)據(jù)集的異常值
outliers=p['fliers'][0].get_xydata()#get_xydata()把異常值返回到一個二維數(shù)組中
outliers.shape
(763, 2)
outliers[:,1:].min() #看看最小的異常值是多少
1.3534146969999998
sns.distplot(df['RevolvingUtilizationOfUnsecuredLines'][(df.SeriousDlqin2yrs == 1) & (df.RevolvingUtilizationOfUnsecuredLines<1.4)], bins=20,color='red')
sns.distplot(df['RevolvingUtilizationOfUnsecuredLines'][(df.SeriousDlqin2yrs == 0) & (df.RevolvingUtilizationOfUnsecuredLines<1.4)], bins=20,color='blue')
<matplotlib.axes._subplots.AxesSubplot at 0x1027f5f8>
output_21_1.png

未違約人群,RevolvingUtilizationOfUnsecuredLines屬性的最高頻率在0附近;違約人群,RevolvingUtilizationOfUnsecuredLines的最高頻率在1附近。

#計算每個屬性的異常值數(shù)量和最小的異常值
col_min={}
for  feature in features:
    p=df[[feature]].boxplot(return_type='dict')
    outliers=p['fliers'][0].get_xydata()
    pmin=outliers[:,1:].min()
    col_min[feature]=[outliers.shape[0],pmin]
output_23_0.png
col_min
{'DebtRatio': [31311, 1.9080459769999998],
 'MonthlyIncome': [9149, 12646.0],
 'NumberOfDependents': [13336, 3.0],
 'NumberOfOpenCreditLinesAndLoans': [3980, 21.0],
 'NumberOfTime30-59DaysPastDueNotWorse': [23981, 1.0],
 'NumberOfTime60-89DaysPastDueNotWorse': [7604, 1.0],
 'NumberOfTimes90DaysLate': [8338, 1.0],
 'NumberRealEstateLoansOrLines': [793, 6.0],
 'RevolvingUtilizationOfUnsecuredLines': [763, 1.3534146969999998],
 'age': [45, 97.0]}
#結(jié)合異常值和該屬性上的數(shù)值分布,選定取值范圍作圖。因為每個屬性的選取范圍和bins不同,所以不進(jìn)行統(tǒng)一繪圖,
而是一個一個繪制。
sns.distplot(df['DebtRatio'][(df.SeriousDlqin2yrs == 1) & (df.DebtRatio<5)], bins=20,color='red')
sns.distplot(df['DebtRatio'][(df.SeriousDlqin2yrs == 0) & (df.DebtRatio<5)], bins=20,color='blue')
<matplotlib.axes._subplots.AxesSubplot at 0xa7cfef0>
output_25_1.png
兩組人群在DebtRatio屬性上的分布相似,最高頻率在0附近,后逐漸降低
sns.distplot(df['NumberOfOpenCreditLinesAndLoans'][(df.SeriousDlqin2yrs == 1) & (df.NumberOfOpenCreditLinesAndLoans<30)], bins=30,color='red')
sns.distplot(df['NumberOfOpenCreditLinesAndLoans'][(df.SeriousDlqin2yrs == 0) & (df.NumberOfOpenCreditLinesAndLoans<30)], bins=30,color='blue')
<matplotlib.axes._subplots.AxesSubplot at 0x11eca3c8>
output_27_1.png
在NumberOfOpenCreditLinesAndLoans屬性上,兩組人群分布相似,最高頻率都是5-8之間
sns.distplot(df['age'][df.SeriousDlqin2yrs == 1] ,bins=50,color='red')
sns.distplot(df['age'][df.SeriousDlqin2yrs == 0], bins=50,color='blue')
<matplotlib.axes._subplots.AxesSubplot at 0x137bbfd0>
output_29_1.png
sns.distplot(df['NumberOfTime30-59DaysPastDueNotWorse'][(df.SeriousDlqin2yrs == 1) & (df['NumberOfTime30-59DaysPastDueNotWorse']<10)], bins=10,color='red')
sns.distplot(df['NumberOfTime30-59DaysPastDueNotWorse'][(df.SeriousDlqin2yrs == 0) & (df['NumberOfTime30-59DaysPastDueNotWorse']<10)], bins=10,color='blue')
<matplotlib.axes._subplots.AxesSubplot at 0xbb45908>
output_30_1.png
sns.distplot(df['NumberOfTime60-89DaysPastDueNotWorse'][(df.SeriousDlqin2yrs == 1) & (df['NumberOfTime60-89DaysPastDueNotWorse']<10)], bins=10,color='red')
sns.distplot(df['NumberOfTime60-89DaysPastDueNotWorse'][(df.SeriousDlqin2yrs == 0) & (df['NumberOfTime60-89DaysPastDueNotWorse']<10)], bins=10,color='blue')
<matplotlib.axes._subplots.AxesSubplot at 0xbf33940>
output_31_1.png
sns.distplot(df['NumberOfTimes90DaysLate'][(df.SeriousDlqin2yrs == 1) & (df.NumberOfTimes90DaysLate<10)], bins=10,color='red')
sns.distplot(df['NumberOfTimes90DaysLate'][(df.SeriousDlqin2yrs == 0) & (df.NumberOfTimes90DaysLate<10)], bins=10,color='blue')
<matplotlib.axes._subplots.AxesSubplot at 0xa5992b0>
output_32_1.png
sns.distplot(df['NumberRealEstateLoansOrLines'][(df.SeriousDlqin2yrs == 1) & (df.NumberRealEstateLoansOrLines<10)], bins=10,color='red')
sns.distplot(df['NumberRealEstateLoansOrLines'][(df.SeriousDlqin2yrs == 0) & (df.NumberRealEstateLoansOrLines<10)], bins=10,color='blue')
<matplotlib.axes._subplots.AxesSubplot at 0xa7aa2e8>
output_33_1.png
其余幾個屬性上,兩類人群的分布都是相近的,不再贅述。和本文采用的是不同分析方法,
前者按各個屬性對借貸者分組,查看不同類別在每一組的分布。本文是先進(jìn)行分類,再查看兩個類別中各個屬性的分布。
。第一種方法使用數(shù)字,能看出更多信息。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 國家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報批稿:20170802 前言: 排版 ...
    庭說閱讀 12,496評論 6 13
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,678評論 19 139
  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標(biāo)簽?zāi)J(rèn)的外補(bǔ)...
    _Yfling閱讀 14,179評論 1 92
  • 這張導(dǎo)圖是有機(jī)化學(xué)中最基礎(chǔ)的幾種物質(zhì)。中心圖是臉譜,因為有機(jī)化學(xué)對于化學(xué)就像是臉譜對于京劇一樣重要。第一分支是甲烷...
    陳虹宇_e51c閱讀 2,295評論 0 1

友情鏈接更多精彩內(nèi)容