Pyspark数据分析之信用卡月收入统计
信用卡逾期分析
from pyspark import SparkConf,SparkContext
conf=SparkConf().setAppName('PreofOverdue').setMaster('local[*]')
sc=SparkContext(conf=conf)
从HDFS读数据
data=sc.textFile('hdfs://localhost:9000/bigwork/traindata.csv').map(lambda x:x.split(','))\
.filter(lambda x:x[3]!='age')
统计不同分段月收入逾期、未逾期人数
RES=[]
#statistic of MonthlyIncome-Overdue
for i in range(0,35000,5000):
#filter对月收入是否在i-i+5000范围判断,获得在该范围的样本
mi0=data.filter(lambda x:float(x[5])>=i and float(x[5])<i+5000)
#groupBy以标签值进行分组,返回的数据中前者是标签,后者是属于该标签的样本集合;
# 然后通过map函数获得标签x[0]和属于该标签样本数量
mi0num=mi0.groupBy(lambda x:x[2]).map(lambda x:[x[0],len(list(x[1]))]).collect()
RES.append({str(i)+"-"+str(i+5000):mi0num})
print("MonthlyIncome-Overdue:\n",RES)
统计家庭人数-逾期/未逾期人数
#statistic of NumberofFamily-Overdue
RES=[]
for i in range(0,5):
mi0=data.filter(lambda x:float(x[8])==i)
mi0num=mi0.groupBy(lambda x:x[2]).map(lambda x:[x[0],len(list(x[1]))]).collect()
RES.append({i+1:mi0num})
print("NumberofFamily-Overdue:\n",RES)
分析家庭只有1个人且逾期的样本与月收入的关系
#single man - overdue
RES=[]
#过滤获得标签为1,家庭人数为1的样本
data=data.filter(lambda x:float(x[2])==1 and float(x[8])==0)
d=data.collect()
#statistic of MonthlyIncome-Overdue
for i in range(0,35000,5000):
mi0=len(data.filter(lambda x:float(x[5])>=i and float(x[5])<i+5000).collect())
RES.append({str(i)+"-"+str(i+5000):mi0})
print("SinglemanofOverdue-Income:\n",RES)