首页 > 其他分享 >数据分析第七章

数据分析第七章

时间:2023-03-12 23:33:31浏览次数:44  
标签:数据分析 plt pd labels kmeans airline 第七章 data

航空公司客户价值分析

数据探索

import pandas as pd
datafile = r"D:\py_project\a_三下\air_data.csv"
resultfile = r'D:\py_project\a_三下\explore.csv'

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

explore = data.describe(percentiles =[],include = 'all').T
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 ('各年份会员入会人数3141')
plt.show()

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('会员性别比例3141')
plt.show()

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('各等级人数3141')
plt.show()

age = data['AGE'].dropna()
age = age.astype('int64')
fig = plt.figure(figsize = (5,10))
plt.boxplot(age, patch_artist = True,labels = ['会员年龄'], 
            boxprops={'facecolor':'lightblue'})
plt.title('会员年龄分布箱型图3141')
plt.grid(axis='y')
plt.show()

 

  

飞行次数及飞行公里数

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 = ['时长'],
            boxprops = {'facecolor':'lightblue'})
plt.title('会员最后乘机至结束时长分布箱型图3152')

plt.grid(axis='y')
plt.show()
plt.close

fig = plt.figure(figsize=(5,8))
plt.boxplot(fc,
            patch_artist=True,
            labels = ['飞行次数'],
            boxprops={'facecolor':'lightblue'})
plt.title('会员飞行次数分布箱型图3141')
plt.grid(axis='y')
plt.show()
plt.close

fig = plt.figure(figsize=(5,10))
plt.boxplot(sks,
            patch_artist=True,
            labels=['总飞行公里数'],
            boxprops = {'facecolor':'lightblue'})
plt.title('客户总飞行公里数箱型图3141')
plt.grid(axis='y')
plt.show()
plt.close

 

 相关性系数矩阵及热力图

#%% 相关系数热力图
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.title('热力图3141')
plt.show()
plt.close

 

清洗空值及异常值

import numpy as np
import pandas as pd
datafile=r"D:\py_project\a_三下\air_data.csv"
cleanedfile=r"D:\py_project\a_三下\air_data.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)

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
airline = airline_notnull[(index1 | index2)&index3&~index4]
print('数据清洗后数据的形状为:',airline.shape)

airline.to_csv(cleanedfile)

 

 

属性选择、构造与数据标准化

cleanedfile=r"D:\py_project\a_三下\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())

# 属性构造,数据标准化
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('构建的LRFMC属性前5行为:\n',airline_features.head())

from sklearn.preprocessing import StandardScaler
data = StandardScaler().fit_transform(airline_features)
np.savez(r'D:\py_project\a_三下\airline_scale.npz',data) print('标准化后LRFMC 5个属性为:\n',data[:5,:])

 

 

 

 

聚类

from sklearn.cluster import KMeans  # 导入kmeans算法
# 读取标准化后的数据
airline_scale = np.load(r'D:\py_project\a_三下\airline_scale.npz')['arr_0']
k = 5  # 确定聚类中心数

# 构建模型,随机种子设为123
kmeans_model = KMeans(n_clusters=k,random_state=123)
fit_kmeans = kmeans_model.fit(airline_scale)  # 模型训练

# 查看聚类结果
kmeans_cc = kmeans_model.cluster_centers_  # 聚类中心
print('各类聚类中心为:\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)

 

 

雷达图

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])
# 由于雷达图要保证数据闭合,因此再添加L列,并转换为 np.ndarray
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('客户特征分析雷达图3141')
plt.legend(legen)
plt.show()
plt.close

 

标签:数据分析,plt,pd,labels,kmeans,airline,第七章,data
From: https://www.cnblogs.com/yunliz/p/17209758.html

相关文章

  • 第七章 --- 航空预测
    1.数据描述与探索 importmatplotlib.pyplotaspltimportnumpyasnpimportpandasaspd#对数据进行基本的探索#返回缺失值个数以及最大最小值importpandasa......
  • 第七章
    7-1数据探索#对数据进行基本的探索#返回缺失值个数以及最大、最小值importpandasaspddatafile='D:/anaconda/python-work/Three/air_data.csv'#航空原始数据,第一......
  • 第七章(第三周)
                                         ......
  • 数据分析第七章实践
    importpandasaspddatafile='C:/Users/Lenore/Desktop/data/air_data.csv'resultfile='C:/Users/Lenore/Desktop/data/explore.csv'data=pd.read_csv(datafile,enco......
  • 第三周——航空数据分析
    importpandasaspddatafile=r"D:\Weixin\WeChatFiles\wxid_cg9y4qd0yxhb22\FileStorage\File\2023-03\air_data.csv"#航空原始数据,第一行为属性标签resultfile......
  • #yyds干货盘点#数据分析报表怎么做
    1.明确报表目的和受众在开始制作报表之前,首先需要明确报表的目的和受众。这有助于你选择适当的指标、图表类型和语言风格,以确保报表能够传达想要的信息并被受众所理解。2.选......
  • 数据分析
    数据清洗:importnumpyasnpimportpandasaspddatafile='D:/WeChatFiles/WeChatFiles/wxid_jomb9ver281c22/FileStorage/File/2023-03/air_data.csv'cleanedfile='D:/......
  • 【数据分析:工具篇】NumPy(1)NumPy介绍
    (【数据分析:工具篇】NumPy(1)NumPy介绍)NumPy介绍NumPy(NumericalPython)是Python的一个开源的科学计算库,它主要用于处理大规模的多维数组以及矩阵操作。NumPy是在Python中进......
  • 数据分析基础笔记 - 数据清洗
    一、读取文件,预处理数据集数据清洗就是对数据的质量进行检查和处理。脏数据定义:由于记录或者储存的原因,导致部分数据缺失、重复、异常、错误,没有分析意义,就叫做“脏数......
  • [学习笔记]《C++ Primer》第七章 类
    thisthis是常量指针,指向非常量版本的类MyClass*const成员函数(memberfunction)所有成员都必须在类的内部声明,但成员函数体可以定义在类内或类外。->成员函数的调用:调......