一、读取数据
代码:
import pandas as pd
datafile = 'F:\大数据分析\\air_data.csv'
resultfile = 'F:\大数据分析\\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)
print(explore)
运行结果:
二、分析数据并绘制基本图像
代码:
from datetime import datetime
import matplotlib.pyplot as plt
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(' 3138')
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('会员性别比例 3138')
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('会员各级别人数 3138')
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 = ['会员年龄'],
boxprops = {'facecolor' :'lightblue'})
plt.title('会员年龄分布箱型图 3138')
plt.grid(axis='y')
plt.show()
plt.close
运行结果“
三、客户乘机数据分析箱型图
代码:
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('会员最后乘机至结束时长分布箱型图 3138')
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('会员飞行次数分布箱型图 3138')
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('客户总飞行公里数箱型图 3138')
plt.grid(axis='y')
plt.show()
plt.close
运行结果:
四、会员积分数据分析直方图:
代码:
# 提取会员积分兑换次数
ec = data['EXCHANGE_COUNT']
# 绘制会员兑换积分次数直方图
fig = plt.figure(figsize=(8,5))
plt.hist(ec,bins=5,color='#0504aa')
plt.xlabel('兑换次数')
plt.ylabel('会员人数')
plt.title('会员兑换积分次数分布直方图 3138')
plt.show()
plt.close
# 提取会员总累计积分
ps = data['Points_Sum']
# 绘制会员总累计积分箱型图
fig = plt.figure(figsize=(5,8))
plt.boxplot(ps,
patch_artist=True,
labels = ['总累计积分'],
boxprops = {'facecolor' : 'lightblue'})
plt.title('客户总累计积分箱型图 3138')
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']]
agel = data['AGE'].fillna(0)
data_corr['AGE'] = agel.astype('int64')
data_corr['ffp_year'] = ffp_year
# 计算相关性矩阵
dt_corr = data_corr.corr(method='pearson')
print('相关性矩阵为:\n 3138',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('热力图 3138')
plt.show()
plt.close
运行结果:
六、进行数据清洗
代码:
import numpy as np
import pandas as pd
datafile ='F:\大数据分析\\air_data.csv'
cleanedfile = 'F:\大数据分析\\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)
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)
运行结果:
七、代码:
import pandas as pd
import numpy as np
cleanedfile = 'F:\大数据分析\\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('F:\大数据分析\\airline_scaple.npz',data)
print('标准化后LRFMC 5个属性为: \n',data[:5,:])
结果:
九、聚类
代码:
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
# 读取标准化后的数据
airline_scale = np.load('F:\大数据分析\\airline_scaple.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)
结果:
十、雷达图
代码:
%matplotlib inline
import matplotlib.pyplot as plt
# 客户分群雷达图
labels = ['ZL','ZR','ZF','ZM','ZC']
cluster_center = pd.concat([cluster_center, cluster_center[['ZL']]],axis=1)
legen = ['客户群'+str(i+1) for i in cluster_center.index]
lstype = ['-','--',(0,(3,5,1,5,1,5)),':','-.']
kinds = list(cluster_center.iloc[:,0])
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
# 画线
ax.set_thetagrids(angle * 180 / np.pi,labels)
plt.title('客户特征分析雷达图 3138')
plt.legend(legen)
plt.show()
plt.close
结果:
客户流失:
一、读取数据:
# 读取数据文件
telcom=pd.read_csv(r"F:\大数据分析\\WA_Fn-UseC_-Telco-Customer-Churn.csv")
telcom.head()
结果:
二、
# 查看数据集大小
telcom.shape
# 获取数据类型的描述统计信息
telcom.describe()
# 查找缺失值
pd.isnull(telcom).sum()
telcom['Churn'].value_counts()
# 查看数据集类型
telcom.info()
三、再次查看是否有缺失值
pd.isnull(telcom["TotalCharges"]).sum()
删除缺失值所在行
telcom.dropna(inplace=True)
telcom.shape
数据归一化处理
telcom['Churn'].replace(to_replace = 'Yes', value = 1,inplace = True)
telcom['Churn'].replace(to_replace = 'No', value = 0,inplace = True)
telcom['Churn'].head()
四、数据可视化呈现
查看流失客户占比
churnvalue=telcom["Churn"].value_counts()
labels=telcom["Churn"].value_counts().index
rcParams["figure.figsize"]=6,6
plt.pie(churnvalue,labels=labels,colors=["whitesmoke","yellow"], explode=(0.1,0),autopct='%1.1f%%', shadow=True)
plt.title("Proportions of Customer Churn 3138")
plt.show()
结果:
性别、老年人、配偶、亲属对流客户流失率的影响
f, axes = plt.subplots(nrows=2, ncols=2, figsize=(10,10))
plt.subplot(2,2,1)
gender=sns.countplot(x="gender",hue="Churn",data=telcom,palette="Pastel2") # palette参数表示设置颜色,这里设置为主题色Pastel2
plt.xlabel("gender")
plt.title("Churn by Gender 3138")
plt.subplot(2,2,2)
seniorcitizen=sns.countplot(x="SeniorCitizen",hue="Churn",data=telcom,palette="Pastel2")
plt.xlabel("senior citizen")
plt.title("Churn by Senior Citizen 3138")
plt.subplot(2,2,3)
partner=sns.countplot(x="Partner",hue="Churn",data=telcom,palette="Pastel2")
plt.xlabel("partner")
plt.title("Churn by Partner 3138")
plt.subplot(2,2,4)
dependents=sns.countplot(x="Dependents",hue="Churn",data=telcom,palette="Pastel2")
plt.xlabel("dependents")
plt.title("Churn by Dependents 3138")
结果:
# 提取特征
charges=telcom.iloc[:,1:20]
corrDf = charges.apply(lambda x: pd.factorize(x)[0])
corrDf .head()
# 构造相关性矩阵
corr = corrDf.corr()
corr
# 使用热地图显示相关系数
plt.figure(figsize=(20,16))
ax = sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns,
linewidths=0.2, cmap="YlGnBu",annot=True)
plt.title("Correlation between variables 3138")
结果:
标签:12,telcom,第三周,2023.3,plt,airline,pd,data,3138 From: https://www.cnblogs.com/Carina----/p/17208134.html