首页 > 其他分享 >第七章 财政收入影响因素分析及预测

第七章 财政收入影响因素分析及预测

时间:2023-03-12 23:34:15浏览次数:42  
标签:pd 第七章 kmeans cluster airline 财政收入 notnull data 预测

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

相关文章

  • 数据分析第七章
    航空公司客户价值分析数据探索importpandasaspddatafile=r"D:\py_project\a_三下\air_data.csv"resultfile=r'D:\py_project\a_三下\explore.csv'data=pd.......
  • 第七章 --- 航空预测
    1.数据描述与探索 importmatplotlib.pyplotaspltimportnumpyasnpimportpandasaspd#对数据进行基本的探索#返回缺失值个数以及最大最小值importpandasa......
  • 第七章
    7-1数据探索#对数据进行基本的探索#返回缺失值个数以及最大、最小值importpandasaspddatafile='D:/anaconda/python-work/Three/air_data.csv'#航空原始数据,第一......
  • 第七章(第三周)
                                         ......
  • 航空公司价值预测
    importpandasaspddatafile=r'G:\data\data\air_data.csv'resultfile=r'G:\data\data\explore.csv'data=pd.read_csv(datafile,encoding='utf-8')explore=data.des......
  • 数据分析第七章实践
    importpandasaspddatafile='C:/Users/Lenore/Desktop/data/air_data.csv'resultfile='C:/Users/Lenore/Desktop/data/explore.csv'data=pd.read_csv(datafile,enco......
  • m分别使用ESN网络,ESN+RBF神经网络以及ESN+Volterra网络进行数据预测对比仿真
    1.算法描述       ESN是Jaeger于2001年提出一种新型递归神经网络,ESN一经提出便成为学术界的热点,并被大量地应用到各种不同的领域中,包括动态模式分类、机器人控制、......
  • m基于ESN+BP神经网络的数据预测算法matlab仿真,测试数据为太阳黑子变化数据
    1.算法描述       在人工神经网络的发展历史上,感知机(MultilayerPerceptron,MLP)网络曾对人工神经网络的发展发挥了极大的作用,也被认为是一种真正能够使用的人工神......
  • Matlab决策树对空气质量和天气温度及天气数据做交通出行推荐预测
    全文链接:http://tecdat.cn/?p=31784原文出处:拓端数据部落公众号为解决城市交通拥堵问题,本文提出了一种基于Matlab决策树的交通预测方法,我们通过采集上海地区的空气质量......
  • 泰坦尼克号旅客生存概率预测
    数据预处理加载数据集importnumpyasnpimportpandasaspdall_df=pd.read_csv("titanic.csv")部分数据 提取所需要的列cols=['survived','name','pclass',......