1. 程式人生 > 實用技巧 >天池二手車_特徵工程

天池二手車_特徵工程

前面已經做了類別和連續特徵的分析,本文將針對特徵工程進行

匯入資料

import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

#匯入訓練集和測試集
train_data =pd.read_csv('F:\\python\\天池_二手車交易價格預測\\used_car_train_20200313.csv',sep=' ')
test_data=pd.read_csv('F:\\python\\天池_二手車交易價格預測\\used_car_testB_20200421.csv
',sep=' ')

刪除異常值

#異常值處理
def out_proc(data,col_name,scale=3):
    
    def box_plot_out(data_ser,box_scale):
        '''
        data_ser接受pd.Series資料格式
        '''
        iqr=box_scale*(data_ser.quantile(0.75)-data_ser.quantile(0.25))   #0.75分位數的值-0.25分位數的值
        val_low=data_ser.quantile(0.25)-iqr
        val_up
=data_ser.quantile(0.75) + iqr rule_low = (data_ser < val_low) rule_up = (data_ser > val_up) return (rule_low, rule_up), (val_low, val_up) #前面返回異常的pandas.Series 資料,後面返回臨界值 data_n=data.copy() #先複製一個df data_series=data_n[col_name] #某一列的值 rule, value = box_plot_out(data_series, box_scale=scale) index
= np.arange(data_series.shape[0])[rule[0] | rule[1]] #shape[0]是行數,丨是or的意思,真個就是輸出有異常值的索引數 print("Delete number is: {}".format(len(index))) #輸出異常值個數 data_n = data_n.drop(index) #刪除異常值 data_n.reset_index(drop=True, inplace=True) #重新設定索引 print("Now column number is: {}".format(data_n.shape[0])) #刪除異常值之後數值的個數 index_low = np.arange(data_series.shape[0])[rule[0]] #低於臨界值的索引數 outliers = data_series.iloc[index_low] #低於臨界值的值 print("Description of data less than the lower bound is:") print(pd.Series(outliers).describe()) index_up = np.arange(data_series.shape[0])[rule[1]] outliers = data_series.iloc[index_up] print("Description of data larger than the upper bound is:") print(pd.Series(outliers).describe()) fig, ax = plt.subplots(1, 2, figsize=(10, 7)) sns.boxplot(y=data[col_name], data=data, palette="Set1", ax=ax[0]) #某列原來的箱型圖 sns.boxplot(y=data_n[col_name], data=data_n, palette="Set1", ax=ax[1]) #刪除異常值後的箱型圖 return data_n #返回刪除後的值

train_data根據power刪除一些異常值

# 這裡刪不刪同學可以自行判斷
# 但是要注意 test 的資料不能刪 = = 不能掩耳盜鈴是不是
train_data= out_proc(train_data,'power',scale=3)
    
train_data.shape  

訓練集和測試集放在一起,方便構造特徵

#用一列做標籤區分一下訓練集和測試集
train_data['train']=1
test_data['train']=0
data = pd.concat([train_data, test_data], ignore_index=True)

建立汽車使用時間(data['creatDate'] - data['regDate'])

# 不過要注意,資料裡有時間出錯的格式,所以我們需要 errors='coerce'
data['used_time'] = (pd.to_datetime(data['creatDate'], format='%Y%m%d', errors='coerce') - 
                            pd.to_datetime(data['regDate'], format='%Y%m%d', errors='coerce')).dt.days

由於有些樣本有問題,導致使用時間為空,我們計算一下空值的個數

data['used_time'].isnull().sum()  #15054