使用pandas的box_plot去除異常值
更新時(shí)間:2019年12月10日 08:38:12 作者:blerli
今天小編就為大家分享一篇使用pandas的box_plot去除異常值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
我就廢話不多說了,直接上代碼吧!
#-*- coding:utf-8 _*-
"""
@author:Administrator
@file: standard_process.py
@time: 2018/8/9
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
import seaborn as sns
from sklearn.preprocessing import StandardScaler
'''
通過box_plot(盒圖來確認(rèn))異常值
'''
# 獲取項(xiàng)目根目錄
input_data_path = os.path.dirname(os.path.dirname(os.getcwd())) + '/input/'
print(input_data_path)
# 獲取數(shù)據(jù)得位置
month_6_train_path = input_data_path +'month_6_1.csv'
month_6_test_path = input_data_path + 'test_data_6_1.csv'
# 讀取數(shù)據(jù)
data_train = pd.read_csv(month_6_train_path)
data_test = pd.read_csv(month_6_test_path)
# print(data_train.head())
# print(data_test.head())
# 暫時(shí)不考慮省份城市地址
# 月份只有一個(gè)月,暫時(shí)不考慮
# bedrooms 需要看成分類型得數(shù)據(jù)
# 只取出longitude,latitude,price,buildingTypeId,bedrooms,daysOnMarket
# 取出這些數(shù)據(jù);
# train = data_train[['longitude', 'latitude', 'price', 'buildingTypeId', 'bedrooms', 'daysOnMarket']]
# train= train.dropna()
train = data_test[['longitude', 'latitude', 'price', 'buildingTypeId', 'bedrooms', 'daysOnMarket']]
print(train.head())
# print(test.head())
# print(train.isna().sum())
# sns.pairplot(train)
# # sns.pairplot(test)
# plt.show()
# 特征清洗:異常值清理用用箱圖;
# 分為兩步走,一步是單列異常值處理,
# 第二步是多列分組異常值處理
def remove_filers_with_boxplot(data):
p = data.boxplot(return_type='dict')
for index,value in enumerate(data.columns):
# 獲取異常值
fliers_value_list = p['fliers'][index].get_ydata()
# 刪除異常值
for flier in fliers_value_list:
data = data[data.loc[:,value] != flier]
return data
print(train.shape)
train = remove_filers_with_boxplot(train)
print(train.shape)
'''
以上得異常值處理還不夠完善,
完善的異常值處理是分組判斷異常值,
也就是他在單獨(dú)這一列種,還有一種情況是多余不同的分類,他是不是存在異常
所以就需要用到分組獲取數(shù)據(jù)再箱圖處理掉異常數(shù)據(jù);
'''
train = train[pd.isna(train.buildingTypeId) != True]
print(train.shape)
print(train['bedrooms'].value_counts())
'''
3.0 8760
2.0 5791
4.0 5442
1.0 2056
5.0 1828
6.0 429
0.0 159
7.0 82
由于樣本存在不均衡得問題:所以只采用12345數(shù)據(jù):也就是說去掉0,7,6,到時(shí)候測(cè)試數(shù)據(jù)也要做相同得操作;
還有一種是通過下采樣或者是上采樣的方式進(jìn)行,這里暫時(shí)不考慮;
'''
# 只取bedrooms 為1,2,3,4,5 得數(shù)據(jù)
train = train[train['bedrooms'].isin([1,2,3,4,5])]
print(train.shape)
# 利用pivot分組后去掉異常點(diǎn)
def use_pivot_box_to_remove_fliers(data,pivot_columns_list,pivot_value_list):
for column in pivot_columns_list:
for value in pivot_value_list:
# 獲取分組的dataframe
new_data = data.pivot(columns=column,values=value)
p = new_data.boxplot(return_type='dict')
for index,value_new in enumerate(new_data.columns):
# 獲取異常值
fliers_value_list = p['fliers'][index].get_ydata()
# 刪除異常值
for flier in fliers_value_list:
data = data[data.loc[:, value] != flier]
return data
# train = use_pivot_box_to_remove_fliers(train,['buildingTypeId','bedrooms'],['price','daysOnMarket','longitude','latitude'])
print(train.shape)
# print(train.isna().sum())
# 以上就不考慮longitude和latitude的問題了;應(yīng)為房屋的類型以及房間個(gè)數(shù)和經(jīng)緯度關(guān)系不大,但是也不一定,
# 實(shí)踐了一下加上longitude和latitude之后樣本數(shù)據(jù)并沒有減少;
# sns.pairplot(train)
# plt.show()
# 先進(jìn)一步做處理將緯度小于40的去掉
train = train[train.latitude>40]
# --------------------------------》》》
# 對(duì)于數(shù)值類型得用均值填充,但是在填充之前注意一些原本就是分類型數(shù)據(jù)得列
# def fill_na(data):
# for column in data.columns:
# if column.dtype != str:
# data[column].fillna(data[column].mean())
# return data
# 以上是異常值,或者是離群點(diǎn)的處理,以及均值填充數(shù)據(jù)
# 下面將根據(jù)catter圖或者是hist圖來處理數(shù)據(jù)
# # 標(biāo)準(zhǔn)化數(shù)據(jù)
# train = StandardScaler().fit_transform(train)
# # 標(biāo)準(zhǔn)化之后畫圖發(fā)現(xiàn)數(shù)據(jù)分布并沒有變
#
# sns.pairplot(pd.DataFrame(train))
# plt.show()
'''
1:循環(huán)遍歷整個(gè)散點(diǎn)圖用剛才寫好的算法去除點(diǎn);
'''
# 獲取
# def get_outlier(x,y,init_point_count ,distance,least_point_count):
# x_outliers_list = []
# y_outliers_list = []
# for i in range(len(x)):
# for j in range(len(x)):
# d =np.sqrt(np.square(x[i]-x[j])+np.square(y[i]-y[j]))
# # print('距離',d)
# if d <= distance:
# init_point_count +=1
# if init_point_count <least_point_count+1:
# x_outliers_list.append(x[i])
# y_outliers_list.append(y[i])
# print(x[i],y[i])
# init_point_count =0
# return x_outliers_list,y_outliers_list
#
# def circulation_to_remove_outliers(data,list_columns=['longitude','latitude','price','daysOnMarket',]):
# for column_row in list_columns:
# for column_col in list_columns:
# if column_row != column_col:
# x = list(data[column_row])
# y = list(data[column_col])
# x_outliers_list ,y_outliers_list = get_outlier(x,y,0,0.01,2)
# for x_outlier in x_outliers_list:
# data = data[data.loc[:, column_row] != x_outlier]
# for y_outlier in y_outliers_list:
# data = data[data.loc[:, column_col] != y_outlier]
# return data
#
# train = circulation_to_remove_outliers(train)
#
# print(train.shape)
# def get_outlier(x,y,init_point_count ,distance,least_point_count):
# for i in range(len(x)):
# for j in range(len(x)):
# d =np.sqrt(np.square(x[i]-x[j])+np.square(y[i]-y[j]))
# # print('距離',d)
# if d <= distance:
# init_point_count +=1
# if init_point_count <least_point_count+1:
# print(x[i],y[i])
# init_point_count =0
#
# get_outlier(train['longitude'],train['latitude'],0,0.3,1)
# sns.pairplot(train)
# plt.show()
# train = train.dropna()
# print(train.tail())
# train.to_csv('./finnl_processing_train_data_6_no_remove_outliers_test.csv',index=False)
相關(guān)文章
在django項(xiàng)目中,如何單獨(dú)運(yùn)行某個(gè)python文件
這篇文章主要介紹了在django項(xiàng)目中單獨(dú)運(yùn)行某個(gè)python文件的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04
python機(jī)器學(xué)習(xí)實(shí)現(xiàn)oneR算法(以鳶尾data為例)
本文主要介紹了python機(jī)器學(xué)習(xí)實(shí)現(xiàn)oneR算法(以鳶尾data為例),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
Python環(huán)境下安裝PyGame和PyOpenGL的方法
這篇文章主要介紹了Python環(huán)境下安裝PyGame和PyOpenGL的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03
Python創(chuàng)建Excel表和讀取Excel表的基本操作
這篇文章主要介紹了Python創(chuàng)建Excel表和讀取Excel表的基本操作,文中通過代碼示例和圖文結(jié)合的方式講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-07-07
解決python DataFrame 打印結(jié)果不換行問題
這篇文章主要介紹了解決python DataFrame 打印結(jié)果不換行問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04
終于搞懂了Keras中multiloss的對(duì)應(yīng)關(guān)系介紹
這篇文章主要介紹了終于搞懂了Keras中multiloss的對(duì)應(yīng)關(guān)系介紹,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06

