首页 > 其他分享 >航空公司客户价值分析

航空公司客户价值分析

时间:2023-03-12 20:57:34浏览次数:30  
标签:plt 20 航空公司 labels 客户 airline pd 价值 data

# -*- coding: utf-8 -*-
"""
Created on Wed Mar  8 08:46:51 2023

@author: 86184
"""
# 对数据进行基本的探索

# 返回缺失值个数以及最大最小值

import pandas as pd

datafile= r'C:\Users\86184\Desktop\文件集\data\air_data.csv'  # 航空原始数据,第一行为属性标签

resultfile = r'C:\Users\86184\Desktop\文件集\data\explore.csv'  # 数据探索结果表

# 读取原始数据,指定UTF-8编码(需要用文本编辑器将数据装换为UTF-8编码)

data = pd.read_csv(datafile, encoding = 'utf-8')

# 包括对数据的基本描述,percentiles参数是指定计算多少的分位数表(如1/4分位数、中位数等)

explore = data.describe(percentiles = [], include = 'all').T

# describe()函数自动计算非空值数,需要手动计算空值数

explore['null'] = len(data)-explore['count']

explore = explore[['null', 'max', 'min']]

explore.columns = [u'空值数', u'最大值', u'最小值']  # 表头重命名



explore.to_csv(resultfile)  # 导出结果



# 客户信息类别

# 提取会员入会年份
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('各年份会员入会人数  number3013',fontsize=20)

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('会员性别比例  number3013',fontsize=20)

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(left=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('会员各级别人数  number3013',fontsize=20)

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('会员年龄分布箱线图  number3013',fontsize=20)

# 显示y坐标轴的底线

plt.grid(axis='y')

plt.show()

plt.close

 1 lte = data['LAST_TO_END']
 2 
 3 fc = data['FLIGHT_COUNT']
 4 
 5 sks = data['SEG_KM_SUM']
 6 
 7 # 绘制最后乘机至结束时长箱线图
 8 
 9 fig = plt.figure(figsize=(5 ,8))
10 
11 plt.boxplot(lte,
12 
13             patch_artist=True,
14 
15             labels = ['时长'],  # 设置x轴标题
16 
17             boxprops = {'facecolor':'lightblue'})  # 设置填充颜色
18 
19 plt.title('会员最后乘机至结束时长分布箱线图  number3013',fontsize=20)
20 
21 # 显示y坐标轴的底线
22 
23 plt.grid(axis='y')
24 
25 plt.show()
26 
27 plt.close
28 
29 # 绘制客户飞行次数箱线图
30 
31 fig = plt.figure(figsize=(5 ,8))
32 
33 plt.boxplot(fc,
34 
35             patch_artist=True,
36 
37             labels = ['飞行次数'],  # 设置x轴标题
38 
39             boxprops = {'facecolor':'lightblue'})  # 设置填充颜色
40 
41 plt.title('会员飞行次数分布箱线图  number3013',fontsize=20)
42 
43 # 显示y坐标轴的底线
44 
45 plt.grid(axis='y')
46 
47 plt.show()
48 
49 plt.close
50 
51 # 绘制客户总飞行公里数箱线图
52 
53 fig = plt.figure(figsize=(5 ,10))
54 
55 plt.boxplot(sks,
56 
57             patch_artist=True,
58 
59             labels = ['总飞行公里数'],  # 设置x轴标题
60 
61             boxprops = {'facecolor':'lightblue'})  # 设置填充颜色
62 
63 plt.title('客户总飞行公里数箱线图  number3013',fontsize=20)
64 
65 # 显示y坐标轴的底线
66 
67 plt.grid(axis='y')
68 
69 plt.show()
70 
71 plt.close

 

 

 

 

 

 

 1 # 积分信息类别
 2 
 3 # 提取会员积分兑换次数
 4 
 5 ec = data['EXCHANGE_COUNT']
 6 
 7 # 绘制会员兑换积分次数直方图
 8 
 9 fig = plt.figure(figsize=(8 ,5))  # 设置画布大小
10 
11 plt.hist(ec, bins=5, color='#0504aa')
12 
13 plt.xlabel('兑换次数')
14 
15 plt.ylabel('会员人数')
16 
17 plt.title('会员兑换积分次数分布直方图 number3013',fontsize=20)
18 
19 plt.show()
20 
21 plt.close
22 
23 # 提取会员总累计积分
24 
25 ps = data['Points_Sum']
26 
27 # 绘制会员总累计积分箱线图
28 
29 fig = plt.figure(figsize=(5 ,8))
30 
31 plt.boxplot(ps,
32 
33             patch_artist=True,
34 
35             labels = ['总累计积分'],  # 设置x轴标题
36 
37             boxprops = {'facecolor':'lightblue'})  # 设置填充颜色
38 
39 plt.title('客户总累计积分箱线图 number3013',fontsize=20)
40 
41 # 显示y坐标轴的底线
42 
43 plt.grid(axis='y')
44 
45 plt.show()
46 
47 plt.close

 

 

 

 

 1 # 提取属性并合并为新数据集
 2 
 3 data_corr = data[['FFP_TIER','FLIGHT_COUNT','LAST_TO_END',
 4 
 5                   'SEG_KM_SUM','EXCHANGE_COUNT','Points_Sum']]
 6 
 7 age1 = data['AGE'].fillna(0)
 8 
 9 data_corr['AGE'] = age1.astype('int64')
10 
11 data_corr['ffp_year'] = ffp_year
12 
13 # 计算相关性矩阵
14 
15 dt_corr = data_corr.corr(method='pearson')
16 
17 print('相关性矩阵为:\n',dt_corr)
18 
19 # 绘制热力图
20 
21 import seaborn as sns
22 
23 plt.subplots(figsize=(10, 10)) # 设置画面大小
24 
25 sns.heatmap(dt_corr, annot=True, vmax=1, square=True, cmap='Blues')
26 plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
27 plt.title('热力图  number3013',fontsize=20)
28 
29 plt.show()
30 
31 plt.close

 

 

 

 

 1 import numpy as np
 2 import pandas as pd
 3 
 4 datafile = r'C:\Users\86184\Desktop\文件集\data\air_data.csv'  # 航空原始数据路径
 5 cleanedfile = r'C:\Users\86184\Desktop\文件集\data\data_cleaned.csv'  # 数据清洗后保存的文件路径
 6 
 7 # 读取数据
 8 airline_data = pd.read_csv(datafile,encoding = 'utf-8')
 9 print('原始数据的形状为:',airline_data.shape)
10 
11 # 去除票价为空的记录
12 airline_notnull = airline_data.loc[airline_data['SUM_YR_1'].notnull() & 
13                                    airline_data['SUM_YR_2'].notnull(),:]
14 print('删除缺失记录后数据的形状为:',airline_notnull.shape)
15 
16 # 只保留票价非零的,或者平均折扣率不为0且总飞行公里数大于0的记录。
17 index1 = airline_notnull['SUM_YR_1'] != 0
18 index2 = airline_notnull['SUM_YR_2'] != 0
19 index3 = (airline_notnull['SEG_KM_SUM']> 0) & (airline_notnull['avg_discount'] != 0)
20 index4 = airline_notnull['AGE'] > 100  # 去除年龄大于100的记录
21 airline = airline_notnull[(index1 | index2) & index3 & ~index4]
22 print('数据清洗后数据的形状为:',airline.shape)
23 
24 airline.to_csv(cleanedfile)  # 保存清洗后的数据

 

 

 1 import pandas as pd
 2 import numpy as np
 3 
 4 # 读取数据清洗后的数据
 5 cleanedfile = r'C:\Users\86184\Desktop\文件集\data\data_cleaned.csv'  # 数据清洗后保存的文件路径
 6 airline = pd.read_csv(cleanedfile, encoding = 'utf-8')
 7 # 选取需求属性
 8 airline_selection = airline[['FFP_DATE','LOAD_TIME','LAST_TO_END',
 9                                      'FLIGHT_COUNT','SEG_KM_SUM','avg_discount']]
10 print('筛选的属性前5行为:\n',airline_selection.head())
11 
12 
13 
14 # 代码7-8
15 
16 # 构造属性L
17 L = pd.to_datetime(airline_selection['LOAD_TIME']) - \
18 pd.to_datetime(airline_selection['FFP_DATE'])
19 L = L.astype('str').str.split().str[0]
20 L = L.astype('int')/30
21 
22 # 合并属性
23 airline_features = pd.concat([L,airline_selection.iloc[:,2:]],axis = 1)
24 airline_features.columns = ['L','R','F','M','C']
25 print('构建的LRFMC属性前5行为:\n',airline_features.head())
26 
27 # 数据标准化
28 from sklearn.preprocessing import StandardScaler
29 data = StandardScaler().fit_transform(airline_features)
30 np.savez(r'C:\Users\86184\Desktop\文件集\data\airline_scale.npz',data)
31 print('标准化后LRFMC五个属性为:\n',data[:5,:])

 

 

 1 import pandas as pd
 2 import numpy as np
 3 from sklearn.cluster import KMeans  # 导入kmeans算法
 4 
 5 # 读取标准化后的数据
 6 airline_scale = np.load(r'C:\Users\86184\Desktop\文件集\data\airline_scale.npz')['arr_0']
 7 k = 5  # 确定聚类中心数
 8 
 9 # 构建模型,随机种子设为123
10 kmeans_model = KMeans(n_clusters = k,n_jobs=4,random_state=123)
11 fit_kmeans = kmeans_model.fit(airline_scale)  # 模型训练
12 
13 # 查看聚类结果
14 kmeans_cc = kmeans_model.cluster_centers_  # 聚类中心
15 print('各类聚类中心为:\n',kmeans_cc)
16 kmeans_labels = kmeans_model.labels_  # 样本的类别标签
17 print('各样本的类别标签为:\n',kmeans_labels)
18 r1 = pd.Series(kmeans_model.labels_).value_counts()  # 统计不同类别样本的数目
19 print('最终每个类别的数目为:\n',r1)
20 # 输出聚类分群的结果
21 cluster_center = pd.DataFrame(kmeans_model.cluster_centers_,\
22              columns = ['ZL','ZR','ZF','ZM','ZC'])   # 将聚类中心放在数据框中
23 cluster_center.index = pd.DataFrame(kmeans_model.labels_ ).\
24                   drop_duplicates().iloc[:,0]  # 将样本类别作为数据框索引
25 print(cluster_center)
26 
27 
28 # 代码7-10
29 
30 %matplotlib inline
31 import matplotlib.pyplot as plt 
32 # 客户分群雷达图
33 labels = ['ZL','ZR','ZF','ZM','ZC']
34 legen = ['客户群' + str(i + 1) for i in cluster_center.index]  # 客户群命名,作为雷达图的图例
35 lstype = ['-','--',(0, (3, 5, 1, 5, 1, 5)),':','-.']
36 kinds = list(cluster_center.iloc[:, 0])
37 # 由于雷达图要保证数据闭合,因此再添加L列,并转换为 np.ndarray
38 cluster_center = pd.concat([cluster_center, cluster_center[['ZL']]], axis=1)
39 centers = np.array(cluster_center.iloc[:, 0:])
40 
41 # 分割圆周长,并让其闭合
42 n = len(labels)
43 angle = np.linspace(0, 2 * np.pi, n, endpoint=False)
44 angle = np.concatenate((angle, [angle[0]]))
45 labels = np.concatenate((labels, [labels[0]]))
46 # 绘图
47 fig = plt.figure(figsize = (8,6))
48 ax = fig.add_subplot(111, polar=True)  # 以极坐标的形式绘制图形
49 plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
50 plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号 
51 # 画线
52 for i in range(len(kinds)):
53     ax.plot(angle, centers[i], linestyle=lstype[i], linewidth=2, label=kinds[i])
54 # 添加属性标签
55 ax.set_thetagrids(angle * 180 / np.pi, labels)
56 plt.title('客户特征分析雷达图--number:3013',fontsize=20)
57 plt.legend(legen)
58 plt.show()
59 plt.close

 

 

 

标签:plt,20,航空公司,labels,客户,airline,pd,价值,data
From: https://www.cnblogs.com/D753868713/p/17209060.html

相关文章

  • 航空公司客户价值分析
    #-*-coding:utf-8-*-#代码7-1#对数据进行基本的探索#返回缺失值个数以及最大最小值importpandasaspddatafile='D://人工智能/air_data.csv'#航空原......
  • Solon2 分布式事件总线的技术价值?
    分布式事件总线在分布式开发(或微服务开发)时,是极为重要的架构手段。它可以分解响应时长,可以削峰,可以做最终一致性的分布式事务,可以做业务水平扩展。1、分解响应时长比如我......
  • 使用virt-manager 在主机和客户机之间共享文件夹
    导读在本指南中,你将学习如何在virt-manager的KVM、QEMU和libvirt的主机和客户机之间共享文件夹。​​virt-manager​​​应用或软件包使用​​libvirt​......
  • 外贸建站如何提高搜索引擎排名,吸引更多潜在客户?
    在如今全球贸易日益繁荣的背景下,越来越多的企业开始重视外贸建站,并寻求提高搜索引擎排名以吸引更多潜在客户。那么,如何才能有效地提高外贸网站的搜索引擎排名呢?本文将为您详......
  • 使用Go语言创建WebSocket服务器和客户端
    WebSocket是一种新型的网络通信协议,可以在Web应用程序中实现双向通信。在这篇文章中,我们将介绍如何使用Go语言编写一个简单的WebSocket服务器。首先,我们需要使用G......
  • Web客户端开发
    Web开发工具从高层次来看,可以将客户端工具放入以下三大类需要解决的问题中:安全网络—在代码开发期间有用的工具。转换—以某种方式转换代码的工具,例如将一种中间语......
  • virtualbox客户机分辨率无法调整
    单位机器里的VirtualBox,前些日子开始客户机运行时窗口被限制了分辨率,最高只能设置到1024*768。这个分辨率在浏览一些网页时显示不完整,需要用滚动条拖来拖去,非常不方便。......
  • 自动化测试工具Telerik Test Studio R1 2023,让交付的应用“价值”拉满!
    TelerikTestStudio是一个用于功能性Web、桌面和移动测试的直观测试自动化工具,它能轻松地实现自动化测试。同时会为GUI、性能、加载和API测试提供完整的自动化测试解决方......
  • docker 开启远程客户端访问
    配置Docker的服务器开启远程客户端访问:sudovim/etc/systemd/system/multi-user.target.wants/docker.service打开后,添加高亮部分:[Service]Type=notify#thedefaul......
  • 即时通讯系统 -- V1.0客户端全功能实现
    实现了客户端的菜单功能,分为公聊模式私聊模式更新用户名退出并实现了这四个功能,本次的简易即时聊天系统到此结束公聊模式func(client*Client)Public......