Python數(shù)據(jù)預(yù)處理
一、內(nèi)容:
1、數(shù)據(jù)清洗
2、數(shù)據(jù)集成
3、數(shù)據(jù)可視化
二、實(shí)驗(yàn)數(shù)據(jù)
根據(jù)航空公司系統(tǒng)內(nèi)的客戶基本信息、乘機(jī)信息以及積分信息等詳細(xì)數(shù)據(jù),依據(jù)末次飛行日期( LAST_FLIGHT_DATE),以2014年3月31日為結(jié)束時(shí)間,選取寬度為兩年的時(shí)間段作為分析觀測(cè)窗口,抽取觀測(cè)窗口2012年4月1日至2014年3月31日內(nèi)有乘機(jī)記錄的所有客戶的詳細(xì)數(shù)據(jù)形成歷史數(shù)據(jù),分為air_data01.xlsx、air_data02.xlsx總共62988條記錄。其中包含了會(huì)員卡號(hào)、入會(huì)時(shí)間、性別、年齡、會(huì)員卡級(jí)別、工作地城市、工作地所在省份、工作地所在國(guó)家、觀測(cè)窗口結(jié)束時(shí)間、觀測(cè)窗口乘機(jī)積分、飛行公里數(shù)、飛行次數(shù)、飛行時(shí)間、乘機(jī)時(shí)間間隔、平均折扣率等44個(gè)屬性,如下表2-1所示。
三、設(shè)計(jì)方案
1、數(shù)據(jù)清洗:
a.首先將數(shù)據(jù)進(jìn)行統(tǒng)計(jì)性分析,查找每列屬性觀測(cè)值中的空值個(gè)數(shù)最大值、最小值。得到的分析結(jié)果表如下表3-1所示。通過(guò)對(duì)原始數(shù)據(jù)觀察發(fā)現(xiàn)數(shù)據(jù)中存在票價(jià)為空值的記錄,同時(shí)存在票價(jià)最小值為0、折扣率最小值為0但總飛行公里數(shù)大于0的記錄。票價(jià)為空值的數(shù)據(jù)可能是客戶不存在乘機(jī)記錄造成的。其他的數(shù)據(jù)可能是客戶乘坐0折機(jī)票或者積分兌換造成的。
b.緊接著是分別對(duì)air_data01、air_data02兩個(gè)數(shù)據(jù)集進(jìn)行讀取,并進(jìn)行重復(fù)數(shù)據(jù)篩選與刪除,對(duì)繪制箱型圖年齡和票價(jià)為空的記錄等異常值進(jìn)行發(fā)現(xiàn)與刪除,保留清洗后的數(shù)據(jù)。
2.數(shù)據(jù)集成
這一步是將數(shù)據(jù)清洗后的air_data01、air_data02兩個(gè)數(shù)據(jù)集合并存放在一個(gè)數(shù)據(jù)存儲(chǔ)中(cleanedfile_finish.csv),目的是為了便于后續(xù)的數(shù)據(jù)挖掘工作。
3.數(shù)據(jù)可視化
使用數(shù)據(jù)集成后的新產(chǎn)生的多維數(shù)據(jù)集cleanedfile_finish.csv對(duì)數(shù)據(jù)進(jìn)行可視化操作,并對(duì)表格中的統(tǒng)計(jì)數(shù)據(jù)完成直方圖、餅圖、條形圖、箱型圖、熱力圖的繪制。
四、實(shí)驗(yàn)結(jié)論
1、程序源代碼
1)數(shù)據(jù)清洗
a、準(zhǔn)備工作:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
b、數(shù)據(jù)統(tǒng)計(jì)性分析:
datafile= 'air_data01.xlsx' # 航空原始數(shù)據(jù),第一行為屬性標(biāo)簽
resultfile = 'explore.csv' # 數(shù)據(jù)統(tǒng)計(jì)性分析結(jié)果表
data = pd.read_excel(datafile)
datafile2= 'air_data02.xlsx'
resultfile2 = 'explore2.csv'
data2 = pd.read_excel(datafile2)
explore = data.describe(percentiles = [], include = 'all').T # T是轉(zhuǎn)置
explore['null'] = len(data)-explore['count']
explore = explore[['null', 'max', 'min']]
explore.columns = ['空值數(shù)', '最大值', '最小值'] # 表頭重命名
explore.to_csv('resultfile.csv') # 導(dǎo)出結(jié)果
explore2 = data2.describe(percentiles = [], include = 'all').T # T是轉(zhuǎn)置
explore2['null'] = len(data)-explore2['count']
explore2 = explore2[['null', 'max', 'min']]
explore2.columns = ['空值數(shù)', '最大值', '最小值']
explore2.to_csv('resultfile2.csv')
datatemp = pd.concat([explore,explore2],axis=0)
datatemp.to_csv('data_Statistical analysis.csv') # 導(dǎo)出最終結(jié)果
通過(guò)對(duì)原始數(shù)據(jù)觀察發(fā)現(xiàn)數(shù)據(jù)中存在票價(jià)為空值的記錄,同時(shí)存在票價(jià)最小值為0、折扣率最小值為0但總飛行公里數(shù)大于0的記錄。票價(jià)為空值的數(shù)據(jù)可能是客戶不存在乘機(jī)記錄造成的。其他的數(shù)據(jù)可能是客戶乘坐0折機(jī)票或者積分兌換造成的。所以后面我們將對(duì)這一部分?jǐn)?shù)據(jù)進(jìn)行清除操作。
c、對(duì)數(shù)據(jù)集進(jìn)行讀?。?/strong>
df1 = pd.read_excel('air_data01.xlsx')
df2 = pd.read_excel('air_data02.xlsx')
對(duì)重復(fù)數(shù)據(jù)進(jìn)行刪除:
def df_drop(df): #刪除重復(fù)數(shù)據(jù)
print("yunxingle")
df_1 = df.duplicated() #進(jìn)行重復(fù)判斷
print("重復(fù)判斷\n:",df_1)
df_2 = df[df.duplicated()]#顯示重復(fù)數(shù)據(jù)sss
print("\n\n\n重復(fù)數(shù)據(jù)\n",df_2)
df_new = df.drop_duplicates() #刪除重復(fù)數(shù)據(jù)
return df_new
df_drop(df1)
df_drop(df2)
d、對(duì)缺失行進(jìn)行刪除:
def df_kong(df):
df_1 = df.apply(lambda col:sum(col.isnull())/col.size)
print('\n判斷缺失情況:\n\n',df_1)
df_2 = df.dropna(how='any')#刪除所有含有缺失值的行
print(df_2.head(10))
return df_2
df_kong(df1)
df_kong(df2)
e、合并數(shù)據(jù)并保存:
data_new1 = df_kong(df_drop(df1))
data_new2 = df_kong(df_drop(df2))
data_integrated = pd.concat([data_new1,data_new2],axis=1)
data_integrated.to_csv('data_integrated.csv') # 保存清洗后的數(shù)據(jù)
f、異常值清除:
data = pd.read_csv('data_integrated.csv')
# data = data_new1
age = data['AGE'].dropna()
age = age.astype('int64')
# 繪制會(huì)員年齡分布箱型圖
plt.rcParams['font.sans-serif'] = 'SimHei' # 設(shè)置中文顯示
fig = plt.figure(figsize = (5 ,10))
plt.boxplot(age, patch_artist=True,
labels = ['會(huì)員年齡'], # 設(shè)置x軸標(biāo)題
boxprops = {'facecolor':'lightblue'}) # 設(shè)置填充顏色
plt.title('會(huì)員年齡分布箱線圖')
# 顯示y坐標(biāo)軸的底線
plt.grid(axis='y')
plt.show()
plt.close()
# 箱型圖顯示年齡數(shù)據(jù)存在有大于100的異常值,下面予以修正
print('原始數(shù)據(jù)的形狀為:',data.shape)
index = data['AGE'] > 100 # 去除年齡大于100的記錄
data2 = data[~index]
print('數(shù)據(jù)清洗后數(shù)據(jù)的形狀為:',data2.shape)
data2.to_csv('cleanedfile_01.csv') # 保存清洗后的數(shù)據(jù)
age = data2['AGE'].dropna()
age = age.astype('int64')
# 繪制會(huì)員年齡分布箱型圖
plt.rcParams['font.sans-serif'] = 'SimHei' # 設(shè)置中文顯示
fig2 = plt.figure(figsize = (5 ,10))
plt.boxplot(age, patch_artist=True,
labels = ['會(huì)員年齡'], # 設(shè)置x軸標(biāo)題
boxprops = {'facecolor':'lightblue'}) # 設(shè)置填充顏色
plt.title('會(huì)員年齡分布箱線圖')
# 顯示y坐標(biāo)軸的底線
plt.grid(axis='y')
plt.show()
plt.close()
data3 = pd.read_csv('cleanedfile_01.csv',encoding = 'utf-8')
print('原始數(shù)據(jù)的形狀為:',data3.shape)
# 去除票價(jià)為空的記錄
data3_notnull = data3.loc[data3['SUM_YR_1'].notnull() &
data3['SUM_YR_2'].notnull(),:]
print('刪除缺失記錄后數(shù)據(jù)的形狀為:',data3_notnull.shape)
# data3_notnull.to_csv('data3_notnull.csv') # 保存清洗后的數(shù)據(jù)
# 只保留票價(jià)非零的,或者平均折扣率不為0且總飛行公里數(shù)大于0的記錄。
index1 = data3_notnull['SUM_YR_1'] != 0
index2 = data3_notnull['SUM_YR_2'] != 0
index3 = (data3_notnull['SEG_KM_SUM']> 0) & (data3_notnull['avg_discount'] != 0)
cleanedfile_02 = data3_notnull[(index1 | index2) & index3]
print('數(shù)據(jù)清洗后數(shù)據(jù)的形狀為:',cleanedfile_02.shape)
cleanedfile_02.to_csv('cleanedfile_finish1.csv') # 保存清洗后的數(shù)據(jù)
2)數(shù)據(jù)集成
data_new1 = df_kong(df_drop(df1))
data_new2 = df_kong(df_drop(df2))
data_integrated = pd.concat([data_new1,data_new2],axis=1)#數(shù)據(jù)集成
data_integrated.to_csv('data_integrated.csv') # 保存清洗后的數(shù)據(jù)
3)數(shù)據(jù)可視化
a、準(zhǔn)備工作:
import pandas as pd
import matplotlib.pyplot as plt
datafile= 'cleanedfile_finish.csv'
b、各年份會(huì)員入會(huì)人數(shù)直方圖繪制:
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)
# 繪制各年份會(huì)員入會(huì)人數(shù)直方圖
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('入會(huì)人數(shù)')
plt.title('各年份會(huì)員入會(huì)人數(shù)')
plt.show()
plt.close
c、會(huì)員性別比例餅餅圖繪制:
male = pd.value_counts(data['GENDER'])['男']
female = pd.value_counts(data['GENDER'])['女']
# 繪制會(huì)員性別比例餅圖
fig = plt.figure(figsize = (7 ,4)) # 設(shè)置畫(huà)布大小
plt.pie([ male, female], labels=['男','女'], colors=['lightskyblue', 'lightcoral'],
autopct='%1.1f%%')
plt.title('會(huì)員性別比例')
plt.show()
plt.close
d、會(huì)員各級(jí)別人數(shù)條形圖繪制:
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]
# 繪制會(huì)員各級(jí)別人數(shù)條形圖
fig = plt.figure(figsize = (8 ,5)) # 設(shè)置畫(huà)布大小
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('會(huì)員等級(jí)')
plt.ylabel('會(huì)員人數(shù)')
plt.title('會(huì)員各級(jí)別人數(shù)')
plt.show()
plt.close()
e、會(huì)員年齡分布箱型圖繪制:
age = data['AGE'].dropna()
age = age.astype('int64')
# 繪制會(huì)員年齡分布箱型圖
fig = plt.figure(figsize = (5 ,10))
plt.boxplot(age,
patch_artist=True,
labels = ['會(huì)員年齡'], # 設(shè)置x軸標(biāo)題
boxprops = {'facecolor':'lightblue'})
plt.title('會(huì)員年齡分布箱線圖')
plt.grid(axis='y')
plt.show()
plt.close
f、最后乘機(jī)至結(jié)束時(shí)長(zhǎng)箱型圖繪制:
fig = plt.figure(figsize = (5 ,8))
plt.boxplot(lte,最后乘機(jī)至結(jié)束時(shí)長(zhǎng)箱線圖
patch_artist=True,
labels = ['時(shí)長(zhǎng)'], # 設(shè)置x軸標(biāo)題
boxprops = {'facecolor':'lightblue'})
plt.title('會(huì)員最后乘機(jī)至結(jié)束時(shí)長(zhǎng)分布箱線圖')
plt.grid(axis='y')
plt.show()
plt.close
g、客戶飛行次數(shù)箱型圖繪制:
fig = plt.figure(figsize = (5 ,8))
plt.boxplot(fc,
patch_artist=True,
labels = ['飛行次數(shù)'],
boxprops = {'facecolor':'lightblue'})
plt.title('會(huì)員飛行次數(shù)分布箱線圖')
# 顯示y坐標(biāo)軸的底線
plt.grid(axis='y')
plt.show()
plt.close
h、客戶總飛行公里數(shù)箱型圖繪制:
fig = plt.figure(figsize = (5 ,10))
plt.boxplot(sks,
patch_artist=True,
labels = ['總飛行公里數(shù)'],
boxprops = {'facecolor':'lightblue'})
plt.title('客戶總飛行公里數(shù)箱線圖')
# 顯示y坐標(biāo)軸的底線
plt.grid(axis='y')
plt.show()
plt.close
i、會(huì)員兌換積分次數(shù)直方圖繪制:
ec = data['EXCHANGE_COUNT']
fig = plt.figure(figsize = (8 ,5))
plt.hist(ec, bins=5, color='#0504aa')
plt.xlabel('兌換次數(shù)')
plt.ylabel('會(huì)員人數(shù)')
plt.title('會(huì)員兌換積分次數(shù)分布直方圖')
plt.show()
plt.close
j、計(jì)算相關(guān)矩陣并繪制熱力圖:
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('相關(guān)性矩陣為:\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.show()
plt.close
2、程序相關(guān)結(jié)果展示
1)數(shù)據(jù)清洗
a、數(shù)據(jù)統(tǒng)計(jì)性分析:
通過(guò)對(duì)原始數(shù)據(jù)觀察發(fā)現(xiàn)數(shù)據(jù)中存在票價(jià)為空值的記錄,同時(shí)存在票價(jià)最小值為0、折扣率最小值為0但總飛行公里數(shù)大于0的記錄。票價(jià)為空值的數(shù)據(jù)可能是客戶不存在乘機(jī)記錄造成的。其他的數(shù)據(jù)可能是客戶乘坐0折機(jī)票或者積分兌換造成的。所以后面我們將對(duì)這一部分?jǐn)?shù)據(jù)進(jìn)行清除操作。
c、重復(fù)值分析:
如圖示,顯示有重復(fù)數(shù)據(jù),下面我們將重復(fù)數(shù)據(jù)進(jìn)行展示。可以看出air_data01有71行重復(fù)數(shù)據(jù)。air_data02有1738行重復(fù)數(shù)據(jù)。
我們對(duì)重復(fù)數(shù)據(jù)執(zhí)行刪除操作。
d、缺失行進(jìn)行分析:
根據(jù)觀察,表格air_data01存在部分?jǐn)?shù)據(jù)缺失,因?yàn)閿?shù)據(jù)量較為龐大,所以我們對(duì)所有缺失的數(shù)據(jù)執(zhí)行行刪除操作。
e、重復(fù)數(shù)據(jù)與缺失數(shù)據(jù)刪除前后數(shù)據(jù)對(duì)比:
f、異常值清除:
根據(jù)會(huì)員年齡分布箱型圖,可以看出大部分會(huì)員年齡集中在30~50歲之間,極少量的會(huì)員年齡小于20歲或高于60歲,且存在一個(gè)超過(guò)100歲的異常數(shù)據(jù)。我們對(duì)該AGE數(shù)據(jù)中大于100的進(jìn)行刪除,所得結(jié)果如下圖所示。
2)數(shù)據(jù)集成
保存數(shù)據(jù)到‘cleanedfile_finish1.csv’用于后續(xù)數(shù)據(jù)可視化。
3)數(shù)據(jù)可視化
a、各年份會(huì)員入會(huì)人數(shù)直方圖繪制:
可以發(fā)現(xiàn)入會(huì)人數(shù)大致是隨著年份的增加而增加,在2012年達(dá)到頂峰。2009年與2013年與趨勢(shì)不符,有可能是采樣的問(wèn)題,有可能是其他類似政策的問(wèn)題
b、會(huì)員性別比例餅餅圖繪制:
可以發(fā)現(xiàn)入會(huì)男性比例遠(yuǎn)遠(yuǎn)高于女性。
c、會(huì)員各級(jí)別人數(shù)條形圖繪制:
可以看出絕大多數(shù)會(huì)員為4級(jí)會(huì)員,僅有少數(shù)5級(jí)或者6級(jí)會(huì)員
d、箱型圖繪制
由會(huì)員年齡分布箱線圖可以看出絕大多數(shù)年齡位于30~50歲之間
最后一次乘機(jī)時(shí)間至觀測(cè)窗口時(shí)長(zhǎng)越短,表示客戶對(duì)航空公司越滿意。時(shí)間間隔越短同時(shí)也表示該客戶可能是高價(jià)值客戶。并且還可以從這個(gè)屬性中看到公司的發(fā)展問(wèn)題,如果時(shí)間間隔短的客戶越來(lái)越少,說(shuō)明該公司的運(yùn)營(yíng)出現(xiàn)了問(wèn)題,需要及時(shí)調(diào)整營(yíng)銷策略。
通過(guò)圖像可以很清晰的發(fā)現(xiàn):客戶的飛行次數(shù)與總飛行里程數(shù)明顯分為兩個(gè)群體,大部分客戶集中在箱型圖中的箱體中,少數(shù)客戶位于箱體上方,這部分客戶很可能就是高價(jià)值客戶。
h、會(huì)員兌換積分次數(shù)直方圖繪制:
通過(guò)圖形可以看出:絕大多數(shù)兌換次數(shù)位于0~10次之間,這表明大部分客戶很少進(jìn)行積分兌換。
i、計(jì)算相關(guān)矩陣并繪制熱力圖:
通過(guò)熱力圖可以看出:部分屬性之間存在強(qiáng)相關(guān)性,比如總飛行公里數(shù)與票價(jià)收入,總累計(jì)積分,飛行次數(shù)??梢酝ㄟ^(guò)這些關(guān)聯(lián)性強(qiáng)的屬性進(jìn)一步對(duì)數(shù)據(jù)進(jìn)行挖掘分析。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-758994.html
如需要實(shí)驗(yàn)代碼和數(shù)據(jù),請(qǐng)私信,無(wú)償提供,僅供學(xué)習(xí)交流哦~文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-758994.html
到了這里,關(guān)于Python數(shù)據(jù)挖掘 數(shù)據(jù)預(yù)處理案例(以航空公司數(shù)據(jù)為例)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!