1.總結(jié)
流程 | 具體操作 |
---|---|
基本查看 | 查看缺失值、查看重復(fù)值、查看數(shù)值類型 |
預(yù)處理 | 缺失值處理(確定是否處理后,使用篩選方式刪除)拆分?jǐn)?shù)據(jù) 、標(biāo)簽的特征處理(處理成0/1格式)、特征工程(one-hot編碼) |
數(shù)據(jù)分析 | groupby分組求最值數(shù)據(jù)、seaborn可視化 |
預(yù)測 | 拆分?jǐn)?shù)據(jù)集、建立模型、訓(xùn)練模型、預(yù)測、評估模型 |
數(shù)量查看:條形圖
占比查看:餅圖
數(shù)據(jù)分區(qū)分布查看:概率密度函數(shù)圖
2.數(shù)據(jù)預(yù)處理
2.1 導(dǎo)入數(shù)據(jù)集與庫并基本查看數(shù)據(jù)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
dataset = pd.read_csv('data.csv')
2.2 數(shù)據(jù)的基本查看
# 整體查看:tag標(biāo)簽中數(shù)據(jù)需要拆分、并且存在缺失值
dataset.head()
# 對數(shù)值類型的變量進(jìn)行查看
dataset.describe()
# 查看缺失值數(shù)量:缺失值不多,可以直接刪了
dataset[dataset['tag'].notna()]
2.3 缺失值處理與獲取標(biāo)簽值
# 刪選出標(biāo)簽不為NaN的二手車數(shù)據(jù)(因?yàn)槿笔е禂?shù)量不多)
dataset = dataset[dataset["tag"].notna()]
dataset
# 拆分標(biāo)簽
tag_list = []
# apply函數(shù):會自動循環(huán)每一行的數(shù)據(jù) 并且執(zhí)行中間的匿名函數(shù)
dataset['tag'].apply(lambda x:tag_list.extend(x.split("_")))
# 對元素去重,再次轉(zhuǎn)換為列表
tag_list = list(set(tag_list))
# 獲取到所有的標(biāo)簽值
tag_list
2.4 標(biāo)簽的特征處理
與one-hot編碼很類似,但是one-hot編碼只能存在1位有效狀態(tài)
'''
新增列:每個tag標(biāo)簽都是一列
若存在這個標(biāo)簽設(shè)置為1;不存在為0
'''
# 創(chuàng)建DataFrame,列名稱是tag_list里的元素
tag_df = pd.DataFrame(columns=tag_list)
# 拼接兩個DataFrame
df = pd.concat([dataset,tag_df],sort=False)
# 將tag_list對應(yīng)的NaN填充為0
df[tag_list] = df[tag_list].fillna(0)
# 將tag中的數(shù)據(jù)處理為數(shù)字(0或1)
# 傳遞的series為一行的數(shù)據(jù)
def set_tag_status(series):
tags = series['tag'].split('_')# 將tag用_進(jìn)行拆分
for t in tags:
# 若這一行存在這個標(biāo)簽,就直接把他改成1
series[t] = 1
return series
# 將df[['tag',*tag_list]]的每一行應(yīng)用到set_tag_status函數(shù)中,刪除'tag'列,最后替換掉df[tag_list]部分
# *tag_list是拆分這個列表
df[tag_list] = df[["tag", *tag_list]].apply(lambda x:set_tag_status(x), axis=1).drop("tag",axis=1)
df = df.drop("tag",axis=1) # 刪除tag列
df.head()
最終效果
2.5 特征工程(one-hot編碼)
什么是ont-hot編碼
One-Hot編碼是分類變量作為二進(jìn)制向量的表示。又稱為一位有效編碼,主要是采用N位狀態(tài)寄存器來對N個狀態(tài)進(jìn)行編碼,每個狀態(tài)都有獨(dú)立的寄存器位,并且在任意時候只有一位有效(設(shè)置為1),無效的狀態(tài)標(biāo)記為0。
# 創(chuàng)建dataframe記錄one-hot編碼
one_hot_df = pd.get_dummies(df['brand'])
# 刪除brand列
df.drop("brand",axis=1,inplace=True)
# 合并兩個dataframe, 以左右兩張表相同索引進(jìn)行合并
df = pd.merge(df, one_hot_df, left_index=True, right_index=True)
df
3.數(shù)據(jù)分析
3.1 價格分析
分析平均價格最高的前10個品牌
# 分析平均價格最高的前10個品牌
num_top = df.groupby("brand")['price'].mean().sort_values(ascending=False)[:10]
# seaborn繪制條形圖
sns.set(font='SimHei')# 設(shè)置中文字體
fig = plt.figure(figsize=(15,10))# 設(shè)置圖像大小
sns.barplot(x=num_top.index, y=num_top.values) # 繪制條形圖
# plt.xticks(rotation=90) 設(shè)置x刻度軸旋轉(zhuǎn)角度
fig.show()
3.2 銷量分析——銷量分析、銷量占比分析
銷量最多的前10個品牌
# 銷量最多的前10個品牌
amount_top = df["brand"].value_counts(sort=True)[:10]
fig = plt.figure(figsize=(15,10))# 設(shè)置圖像大小
sns.barplot(x=amount_top.index, y=amount_top) # 繪制條形圖
# plt.xticks(rotation=90) 設(shè)置x刻度軸旋轉(zhuǎn)角度
fig.show()
銷量占比分析(餅圖)
# 銷量占比分析(餅圖)
fig = plt.figure(figsize=(15,10))# 設(shè)置圖像大小
plt.pie(amount_top, labels=amount_top.index, autopct="%1.2f%%") # 繪制條形圖;設(shè)置保留兩位小數(shù),數(shù)字1可以不寫,保留小數(shù)點(diǎn)前至少1位數(shù)字(防止報錯)
plt.title("各大品牌車系數(shù)量占有比前10位")
# plt.xticks(rotation=90) 設(shè)置x刻度軸旋轉(zhuǎn)角度
fig.show()
3.3 價格分區(qū)概率分析
繪制直方圖與概率密度函數(shù)圖文章來源:http://www.zghlxwxcb.cn/news/detail-521459.html
# 1.數(shù)據(jù)準(zhǔn)備(基本數(shù)據(jù))
# 獲取大眾品牌記錄
df_dazhong = df[df["brand"] == '大眾']
dazhong_mean = df_dazhong["price"].mean()
dazhong_std = df_dazhong['price'].std()
num_bins = 20 # 條狀圖數(shù)量(分為幾組)
# 2.繪制直方圖
# density 代表是否歸一化:如果沒有歸一化,數(shù)據(jù)會非常大,不成為密度
n, bins, patches = plt.hist(df_dazhong["price"], num_bins, facecolor="green", density=True,alpha=0.5)
# 3.準(zhǔn)備數(shù)據(jù)(概率密度)
from scipy.stats import norm
# 計算概率密度函數(shù)值
y = norm.pdf(bins, dazhong_mean, dazhong_std)
# 4.繪制概率密度函數(shù)圖
plt.plot(bins, y, 'r--')
plt.xlabel('smarts')
plt.ylabel('probability')
plt.title('大眾價格分區(qū)概率分析')
plt.subplots_adjust(left=0.15)
plt.show()
文章來源地址http://www.zghlxwxcb.cn/news/detail-521459.html
4.建立模型:梯度提升回歸算法
# 1.數(shù)據(jù)準(zhǔn)備
# 只要除了預(yù)測值以外的數(shù)據(jù)值
X = df[df.columns.difference(['price'])].values
# 預(yù)測的目標(biāo)值的數(shù)據(jù)
Y = df['price']
# 2.導(dǎo)入所需要的庫
from sklearn.model_selection import train_test_split # 拆分?jǐn)?shù)據(jù)集
from sklearn.ensemble import GradientBoostingRegressor # 梯度提升回歸算法類GBR
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score # 評估函數(shù)
# 3.拆分?jǐn)?shù)據(jù)集
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=666)
# 4.建立模型:
# n_estimators:評估指標(biāo)
gbdt = GradientBoostingRegressor(n_estimators=80)
# 5.訓(xùn)練模型
gbdt.fit(X_train, Y_train)
# 6.預(yù)測
pred = gbdt.predict(X_test)
# 7.評估
print('MSE',mean_squared_error(Y_test,pred))
print('MAE',mean_absolute_error(Y_test,pred))
print('RMSE',np.sqrt(mean_squared_error(Y_test,pred)))
print('R2',r2_score(Y_test,pred))
到了這里,關(guān)于1.Python數(shù)據(jù)分析項目——二手車價格預(yù)測的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!