Task2
本学习笔记为阿里云天池龙珠计划金融风控训练营的学习内容,
学习链接
项目地址
比赛地址
一、 学习大纲
1.数据总体了解:
- 读取数据集并了解数据集大小,原始特征维度;
- 通过info熟悉数据类型;
- 粗略查看数据集中各特征基本统计量;
2.缺失值和唯一值
3.深入数据-查看数据类型
4.数据间相关关系
5.用pandas_profiling生成数据报告
二、 学习内容
1.数据总体了解:
- 读取数据集并了解数据集大小,原始特征维度;
- 通过info熟悉数据类型;
- 粗略查看数据集中各特征基本统计量;
2.缺失值和唯一值
1)概念: 缺失值是指粗糙数据中由于缺少信息而造成的数据的聚类,分组,删失或截断。它指的是现有数据集中某个或某些属性的值是不完全的。
2)判断缺失值→统计缺失值→ 缺失值填充
3)从列表中获取唯一值
3.深入数据-查看数据类型
根据数据的取值情况,我们可以把数据总体分为两大类:类别型数据和数值型数据。
- 类别型数据
类别型特征有时具有非数值关系,有时也具有数值关系。 - 数值型数据
数值型数据又分为连续性和离散型;离散型和非数值型数据用value_counts查看其分布。
4.数据间相关关系
1)特征和特征之间关系
2)特征和目标变量之间关系:分为类别型变量在不同y值上的分布,连续型变量在不同y值上的分布。
三、 代码实例
1.导入数据分析及可视化过程需要的库并读取文件
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
import warnings
warnings.filterwarnings('ignore')
train = pd.read_csv('http://tianchi-media.oss-cn-beijing.aliyuncs.com/dragonball/FRC/data_set/train.csv')
testA = pd.read_csv('http://tianchi-media.oss-cn-beijing.aliyuncs.com/dragonball/FRC/data_set/testA.csv')
train.head()
train.info()
2.总体粗略的查看数据集各个特征的一些基本统计量
data_train.describe()
3.查看数据集中特征缺失值,唯一值等
查看缺失值
print(f'There are {train.isnull().any().sum()} columns in train dataset with missing values.')
There are 22 columns in train dataset with missing values.
have_null_fea_dict = (train.isnull().sum()/len(train)).to_dict()
fea_null_moreThanHalf = {}
for key,value in have_null_fea_dict.items():
if value > 0.5:
fea_null_moreThanHalf[key] = value
fea_null_moreThanHalf
{}
具体的查看缺失特征及缺失率
missing = data_train.isnull().sum()/len(data_train)
missing = missing[missing > 0]
missing.sort_values(inplace=True)
missing.plot.bar()
AxesSubplot:
查看训练集测试集中特征属性只有一值的特征
one_value_fea = [col for col in train.columns if train[col].nunique() <= 1]
one_value_fea_test = [col for col in testA.columns if testA[col].nunique() <= 1]
print(f'There are {len(one_value_fea)} columns in train dataset with one unique value.')
print(f'There are {len(one_value_fea_test)} columns in test dataset with one unique value.')
There are 1 columns in train dataset with one unique value.
There are 1 columns in test dataset with one unique value.
4.查看数值特征的类型
- 数值连续型变量分析
numerical_fea = list(train.select_dtypes(exclude=['object']).columns)
category_fea = list(filter(lambda x: x not in numerical_fea,list(train.columns)))
numerical_serial_fea
category_serial_fea
def get_numerical_serial_fea(data,feas):
numerical_serial_fea = []
numerical_noserial_fea = []
for fea in feas:
temp = train[fea].nunique()
if temp <= 10:
numerical_noserial_fea.append(fea)
continue
numerical_serial_fea.append(fea)
return numerical_serial_fea,numerical_noserial_fea
numerical_serial_fea,numerical_noserial_fea = get_numerical_serial_fea(data_train,numerical_fea)
train['term'].value_counts()#离散型变量
train['regionCode'].value_counts()#离散型变量
train['verificationStatus'].value_counts()#离散型变量
1 309810
2 248968
0 241222
Name: verificationStatus, dtype: int64
f = pd.melt(train, value_vars=numerical_serial_fea)
g = sns.FacetGrid(f, col="variable", col_wrap=2, sharex=False, sharey=False)
g = g.map(sns.distplot, "value")
plt.figure(figsize=(16,12))
plt.suptitle('Transaction Values Distribution', fontsize=22)
plt.subplot(221)
sub_plot_1 = sns.distplot(train['loanAmnt'])
sub_plot_1.set_title("loanAmnt Distribuition", fontsize=18)
sub_plot_1.set_xlabel("")
sub_plot_1.set_ylabel("Probability", fontsize=15)
plt.subplot(222)
sub_plot_2 = sns.distplot(np.log(train['loanAmnt']))
sub_plot_2.set_title("loanAmnt (Log) Distribuition", fontsize=18)
sub_plot_2.set_xlabel("")
sub_plot_2.set_ylabel("Probability", fontsize=15)
- 非数值类别型变量分析
train['grade'].value_counts()
B 233690
C 227118
A 139661
D 119453
E 55661
F 19053
G 5364
Name: grade, dtype: int64
train['subGrade'].value_counts()
C1 50763
B4 49516
B5 48965
B3 48600
C2 47068
C3 44751
C4 44272
B2 44227
B1 42382
C5 40264
A5 38045
A4 30928
D1 30538
D2 26528
A1 25909
D3 23410
A3 22655
A2 22124
D4 21139
D5 17838
E1 14064
E2 12746
E3 10925
E4 9273
E5 8653
F1 5925
F2 4340
F3 3577
F4 2859
F5 2352
G1 1759
G2 1231
G3 978
G4 751
G5 645
Name: subGrade, dtype: int64
train['earliesCreditLine'].value_counts()
Aug-2001 5567
Sep-2003 5403
Aug-2002 5403
Oct-2001 5258
Aug-2000 5246
…
Sep-1957 1
Oct-1954 1
May-1957 1
Jan-1946 1
Nov-1954 1
Name: earliesCreditLine, Length: 720, dtype: int64
5.时间格式数据处理及查看
train['issueDate'] = pd.to_datetime(train['issueDate'],format='%Y-%m-%d')
startdate = datetime.datetime.strptime('2007-06-01', '%Y-%m-%d')
train['issueDateDT'] = train['issueDate'].apply(lambda x: x-startdate).dt.days
testA['issueDate'] = pd.to_datetime(train['issueDate'],format='%Y-%m-%d')
startdate = datetime.datetime.strptime('2007-06-01', '%Y-%m-%d')
testA['issueDateDT'] = testA['issueDate'].apply(lambda x: x-startdate).dt.days
plt.hist(train['issueDateDT'], label='train');
plt.hist(testA['issueDateDT'], label='test');
plt.legend();
plt.title('Distribution of issueDateDT dates');