#代码7-1 数据探索 import pandas as pd datafile = 'data3/air_data.csv' #航空原始数据,第一行为属性标签 resultfile = 'data3/explore.csv' #数据探索结果表 data = pd.read_csv(datafile,encoding = 'utf-8')#读取原始数据,指定UTF-8编码(需要用文本编译器将数据转换为UTF-8编码) #包括对数据的基本描述,percentiles参数是指定计算多少的分位数表(如1/4分位数、中位数等) explore = data.describe(percentiles = [], include = 'all').T explore['null'] = len(data)-explore['count']#describe()函数自动计算非空值数,需要手动计算空值数 explore = explore[['null','max','min']] explore.columns = [u'空值数',u'最大值',u'最小值'] #表头重命名 ''' 这里只选取部分探索结果。 describe()函数自动计算的字段有count(非空值数)、unique(唯一值数)、top(频数最高者)、freq(最高频数)、mean(平均值)、 std(方差)、min(最小值)、50%(中位数)、max(最大值) ''' explore.to_csv(resultfile) #导出结果
#代码7-2 探索客户的基本信息发布情况 #客户信息类别 #提取会员入会年份 import matplotlib.pyplot as plt from datetime import datetime ffp = data['FFP_DATE'].apply(lambda x:datetime.strptime(x,'%Y/%m/%d')) ffp_year = ffp.map(lambda x : x.year) #绘制各年份会员入会人数直方图 fig = plt.figure(figsize=(8,5)) #设置画布大小 plt.rcParams['font.sans-serif'] = 'SimHei' # 设置中文显示 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 plt.hist(ffp_year,bins='auto',color='#0504aa') plt.xlabel('年份') plt.ylabel('入会人数') plt.title('3107各年份会员入会人数') plt.show() plt.close #提取会员不同性别人数 male = pd.value_counts(data['GENDER'])['男'] female = pd.value_counts(data['GENDER'])['女'] #绘制会员性别比例饼图 fig = plt.figure(figsize = (7,4)) plt.pie([male,female],labels=['男','女'],colors=['lightskyblue','lightcoral'],autopct='%1.1f%%') plt.title('3107会员性别比例') plt.show() plt.close() #提取不同级别会员的人数 lv_four = pd.value_counts(data['FFP_TIER'])[4] lv_five = pd.value_counts(data['FFP_TIER'])[5] lv_six = pd.value_counts(data['FFP_TIER'])[6] #绘制会员各级别人数条形图 fig = plt.figure(figsize=(8,5)) plt.bar(x=range(3), height=[lv_four,lv_five,lv_six],width=0.4,alpha=0.8,color='skyblue') plt.xticks([index for index in range(3)],['4','5','6']) plt.xlabel('会员等级') plt.ylabel('会员人数') plt.title('3107会员各级别人数') plt.show() plt.close #提取会员年龄 age = data['AGE'].dropna() age = age.astype('int64') #绘制会员年龄分布箱型图 fig = plt.figure(figsize=(5,10)) plt.boxplot(age,patch_artist=True, labels=['会员年龄'], #设置x轴标题 boxprops={'facecolor' : 'lightblue'}) #设置填充颜色 plt.title('3107会员年龄分布箱型图') plt.grid(axis='y') #显示y坐标轴的底线 plt.show() plt.close
#代码7-3 探索客户乘机信息分布情况 lte = data['LAST_TO_END'] fc = data['FLIGHT_COUNT'] sks = data['SEG_KM_SUM'] #绘制最后乘机至结束时长分布箱型图 fig = plt.figure(figsize=(5,8)) plt.boxplot(lte, patch_artist=True, labels=['时长'], #设置x轴标题 boxprops={'facecolor' : 'lightblue'}) #设置填充颜色 plt.title('3107客户最后乘机至结束时长分布箱型图') plt.grid(axis='y') #显示y坐标轴的底线 plt.show() plt.close #绘制客户飞行次数箱型图 fig = plt.figure(figsize=(5,8)) plt.boxplot(fc, patch_artist=True, labels=['飞行次数'], #设置x轴标题 boxprops={'facecolor' : 'lightblue'}) #设置填充颜色 plt.title('3107客户飞行次数分布箱型图') plt.grid(axis='y') #显示y坐标轴的底线 plt.show() plt.close #绘制客户总飞行公里数箱型图 fig = plt.figure(figsize=(5,8)) plt.boxplot(sks, patch_artist=True, labels=['总飞行公里数'], #设置x轴标题 boxprops={'facecolor' : 'lightblue'}) #设置填充颜色 plt.title('3107客户总飞行公里数分布箱型图') plt.grid(axis='y') #显示y坐标轴的底线 plt.show() plt.close
#代码7-4 ec = data['EXCHANGE_COUNT'] #绘制会员兑换积分次数直方图 fig = plt.figure(figsize=(8,5)) plt.hist(ec,bins=5,color='#0504aa') plt.xlabel('兑换次数') plt.ylabel('会员人数') plt.title('3107会员兑换积分次数分布直方图') plt.show() plt.close #提取会员总累计积分 ps = data['Points_Sum'] #绘制会员总累计积分箱型图 fig = plt.figure(figsize=(5,8)) plt.boxplot(ps, patch_artist=True, labels=['总累计积分'], #设置x轴标题 boxprops={'facecolor' : 'lightblue'}) #设置填充颜色 plt.title('3107客户总累计积分箱型图') plt.grid(axis='y') #显示y坐标轴的底线 plt.show() plt.close
#7—5 data_corr = data[['FFP_TIER','FLIGHT_COUNT','LAST_TO_END', 'SEG_KM_SUM','EXCHANGE_COUNT','Points_Sum']] age1 = data['AGE'].fillna(0) data_corr['AGE'] = age1.astype('int64') data_corr['ffp_year'] = ffp_year #计算相关性矩阵 dt_corr = data_corr.corr(method = 'pearson') print('相关性矩阵为:\n',dt_corr) #绘制热力图 import seaborn as sns plt.subplots(figsize=(10,10)) sns.heatmap(dt_corr,annot=True,vmax=1,square=True,cmap='Blues') plt.show() plt.close
#代码7-6 清洗空值与异常值 import numpy as np import pandas as pd datafile = 'data3/air_data.csv' cleanedfile = 'data3/data_cleaned.csv' airline_data = pd.read_csv(datafile,encoding = 'utf-8') print('原始数据的形状为:', airline_data.shape) #去除票价为空的记录 airline_notnull = airline_data.loc[airline_data['SUM_YR_1'].notnull() & airline_data['SUM_YR_2'].notnull(),:] print('删除缺失记录后数据的形状为:',airline_notnull.shape) #只保留票价非零的,或者平均折扣率不为0且总飞行公里数大于0的记录 index1 = airline_notnull['SUM_YR_1'] != 0 index2 = airline_notnull['SUM_YR_2'] != 0 index3 = (airline_notnull['SEG_KM_SUM'] > 0) & (airline_notnull['avg_discount'] != 0) index4 = airline_notnull['AGE'] > 100 #去除年龄>100的记录 airline = airline_notnull[(index1 | index2) & index3 & ~index4] print('数据清洗后数据的形状为:',airline.shape) airline.to_csv(cleanedfile)
#7-7 import numpy as np import pandas as pd cleanedfile = 'data3/data_cleaned.csv' airline = pd.read_csv(cleanedfile,encoding = 'utf-8') #选取需求属性 airline_selection = airline[['FFP_DATE','LOAD_TIME','LAST_TO_END', 'FLIGHT_COUNT','SEG_KM_SUM','avg_discount']] print('筛选的属性前5行为:\n',airline_selection.head())
#7-8 import pandas as pd L=pd.to_datetime(airline_selection['LOAD_TIME'])-pd.to_datetime(airline_selection['FFP_DATE']) L=L.astype('str').str.split().str[0] L=L.astype('int')/30 airline_features=pd.concat([L,airline_selection.iloc[:,2:]],axis=1) print('3107构建的LRFMC属性前5行为:\n',airline_features.head()) from sklearn.preprocessing import StandardScaler airline_features.columns = airline_features.columns.astype(str) data=StandardScaler().fit_transform(airline_features) np.savez('data3/airline_scale.npz',data) print('3107标准化后LRFMC 5个属性为:\n',data[:5,:])
#7-9 import pandas as pd import numpy as np from sklearn.cluster import KMeans airline_scale=np.load('data3/airline_scale.npz')['arr_0'] k=5 kmeans_model=KMeans(n_clusters=k,random_state=123) fit_kmeans=kmeans_model.fit(airline_scale) kmeans_cc=kmeans_model.cluster_centers_ print('3107各类聚类中心为:\n',kmeans_cc) kmeans_labels=kmeans_model.labels_ print('各样本的类别标签为:\n',kmeans_labels) r1=pd.Series(kmeans_model.labels_).value_counts() print('最终每个类别的数目为:\n',r1) cluster_center=pd.DataFrame(kmeans_model.cluster_centers_,columns=['ZL','ZR','ZF','ZM','ZC']) cluster_center.index=pd.DataFrame(kmeans_model.labels_).drop_duplicates().iloc[:,0] print(cluster_center)
#7-10 %matplotlib inline import matplotlib.pyplot as plt labels=['ZL','ZR','ZF','ZM','ZC'] legen=['客户群'+str(i+1) for i in cluster_center.index] lstype=['-','--',(0,(3,5,1,5,1,5)),':','-.'] kinds=list(cluster_center.iloc[:,0]) cluster_center=pd.concat([cluster_center,cluster_center[['ZL']]],axis=1) centers=np.array(cluster_center.iloc[:,0:]) n=len(labels) angle=np.linspace(0,2*np.pi,n,endpoint=False) angle=np.concatenate((angle,[angle[0]])) fig=plt.figure(figsize=(8,6)) ax=fig.add_subplot(111,polar=True) plt.rcParams['font.sans-serif']=['SimHei'] plt.rcParams['axes.unicode_minus']=False for i in range(len(kinds)): ax.plot(angle,centers[i],linestyle=lstype[i],linewidth=2,label=kinds[i]) #ax.set_thetagrids(angle*180/np.pi,labels) plt.title('3107客户特征分析雷达图') plt.legend(legen) plt.show() plt.close
#客户流失分析 import pandas as pd input_file = 'data3/data_cleaned.csv' output_file = 'data3/selected.xls' data = pd.read_csv(input_file) #选取特征 data['单位里程票价'] = (data['SUM_YR_1'] + data['SUM_YR_2'])/data['SEG_KM_SUM'] data['单位里程积分'] = (data['P1Y_BP_SUM'] + data['L1Y_BP_SUM'])/data['SEG_KM_SUM'] data['飞行次数比例'] = data['L1Y_Flight_Count'] / data['P1Y_Flight_Count'] #第二年飞行次数与第一年飞行次数的比例 data = data[data['FLIGHT_COUNT'] > 6] #筛选出老客户(飞行次数大于6次的为老客户) #选择特征 data = data[['FFP_TIER','飞行次数比例','AVG_INTERVAL','avg_discount','EXCHANGE_COUNT', 'Eli_Add_Point_Sum','单位里程票价','单位里程积分']] data.to_excel(output_file,index=None)
import pandas as pd input_file = 'data3/selected.xls' output_file = 'data3/classfication.xls' data = pd.read_excel(input_file) data['客户类型'] = None for i in range(len(data)): if data['飞行次数比例'][i] < 0.5: data['客户类型'][i] = 0 #0代表已流失 if (data['飞行次数比例'][i] >= 0.5) & (data['飞行次数比例'][i] < 0.9) : data['客户类型'][i] = 1 #1代表准流失 if data['飞行次数比例'][i] >= 0.9: data['客户类型'][i] = 2 #2代表未流失 #导出 data.to_excel(output_file,index=None)
import pandas as pd input_file = 'data3/classfication.xls' output_file = 'data3/std.xls' data = pd.read_excel(input_file) #去掉飞行次数比例 data = data[['FFP_TIER','AVG_INTERVAL','avg_discount','EXCHANGE_COUNT', 'Eli_Add_Point_Sum','单位里程票价','单位里程积分','客户类型']] #标准化 data.loc[:,:'单位里程积分'] = (data.loc[:,:'单位里程积分'] - data.loc[:,:'单位里程积分'].mean(axis = 0)) \ / (data.loc[:,:'单位里程积分'].std(axis = 0)) data.to_excel(output_file,index=None)
import matplotlib.pyplot as plt datafile='data3/std.xls' data=pd.read_excel(datafile) ls=pd.value_counts(data['客户类型'])[0] zls=pd.value_counts(data['客户类型'])[1] wls=pd.value_counts(data['客户类型'])[2] fig=plt.figure(figsize=(7,4)) plt.rcParams['font.sans-serif']='SimHei' plt.rcParams['axes.unicode_minus']=False plt.pie([ls,zls,wls],labels=['0','1','2'],colors=['lightskyblue','lightcoral','lightgreen'],autopct='%1.1f',shadow=True) plt.title('客户流失准流失未流失的比例3107') plt.show() plt.close标签:数据分析,plt,pd,python,labels,airline,第七章,import,data From: https://www.cnblogs.com/pcr-2020310143107/p/17209803.html