import pandas as pd
datafile=r"C:\Users\ying\Desktop\air_data.csv"
resultfile=r"C:\Users\ying\Desktop\explore.xlsx"
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'最小值']#表头重命名
'''
这里只选取部分探索结果。
describe()函数自动计算的字段有count(非空值数)、unique(唯一值数)、top(频数最高者)、
freq(最高频数)、mean(平均值)、std(方差)、min(最小值)、50%(中位数)、max(最大值)
'''
explore.to_csv(resultfile)
#清洗空值与异常值
import numpy as np
import pandas as pd
datafile=r"C:\Users\ying\Desktop\air_data.csv"
cleanedfile=r"C:\Users\ying\Desktop\data_cleaned.xlsx"
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)
#属性选择
cleanedfile=r"C:\Users\ying\Desktop\data_cleaned.xlsx"
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('../tmp/airline_scale.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('../tmp/airline_scale.npz')['arr_0']
k=5
#构建模型,随机种子设为123
kmeans_model=KMeans(n_clusters=k, n_jobs=4, 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.nfarray
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],liFnestyle=lstype[i],linewidth=2,label=kinds[i])
#添加属性标签
ax.set_thetagrids(angle*180/np.pi,labels)
plt.title('客户特征分析雷达图')
plt.legend(legen)
plt.show()
plt.close()
标签:pd,第七章,kmeans,cluster,airline,财政收入,notnull,data,预测 From: https://www.cnblogs.com/----zcy88888/p/17209658.html