python3常用的數(shù)據(jù)清洗方法(小結(jié))
首先載入各種包:
import pandas as pd import numpy as np from collections import Counter from sklearn import preprocessing from matplotlib import pyplot as plt %matplotlib inline import seaborn as sns plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文字體設(shè)置-黑體 plt.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負(fù)號(hào)'-'顯示為方塊的問(wèn)題 sns.set(font='SimHei') # 解決Seaborn中文顯示問(wèn)題
讀入數(shù)據(jù):這里數(shù)據(jù)是編造的
data=pd.read_excel('dummy.xlsx')
本案例的真實(shí)數(shù)據(jù)是這樣的:
對(duì)數(shù)據(jù)進(jìn)行多方位的查看:
實(shí)際情況中可能會(huì)有很多行,一般用head()看數(shù)據(jù)基本情況
data.head() #查看長(zhǎng)啥樣 data.shape #查看數(shù)據(jù)的行列大小 data.describe()
#列級(jí)別的判斷,但凡某一列有null值或空的,則為真 data.isnull().any() #將列中為空或者null的個(gè)數(shù)統(tǒng)計(jì)出來(lái),并將缺失值最多的排前 total = data.isnull().sum().sort_values(ascending=False) print(total) #輸出百分比: percent =(data.isnull().sum()/data.isnull().count()).sort_values(ascending=False) missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent']) missing_data.head(20)
也可以從視覺(jué)上直觀查看缺失值:
import missingno missingno.matrix(data) data=data.dropna(thresh=data.shape[0]*0.5,axis=1) #至少有一半以上是非空的列篩選出來(lái)
#如果某一行全部都是na才刪除: data.dropna(axis=0,how='all')
#默認(rèn)情況下是只保留沒(méi)有空值的行 data=data.dropna(axis=0)
#統(tǒng)計(jì)重復(fù)記錄數(shù) data.duplicated().sum() data.drop_duplicates()
對(duì)連續(xù)型數(shù)據(jù)和離散型數(shù)據(jù)分開(kāi)處理:
data.columns #第一步,將整個(gè)data的連續(xù)型字段和離散型字段進(jìn)行歸類 id_col=['姓名'] cat_col=['學(xué)歷','學(xué)校'] #這里是離散型無(wú)序,如果有序,請(qǐng)參考map用法,一些博客上有寫 cont_col=['成績(jī)','能力'] #這里是數(shù)值型 print (data[cat_col]) #這里是離散型的數(shù)據(jù)部分 print (data[cont_col])#這里是連續(xù)性數(shù)據(jù)部分
對(duì)于離散型部分:
#計(jì)算出現(xiàn)的頻次 for i in cat_col: print (pd.Series(data[i]).value_counts()) plt.plot(data[i])
#對(duì)于離散型數(shù)據(jù),對(duì)其獲取啞變量 dummies=pd.get_dummies(data[cat_col]) dummies
對(duì)于連續(xù)型部分:
#對(duì)于連續(xù)型數(shù)據(jù)的大概統(tǒng)計(jì): data[cont_col].describe() #對(duì)于連續(xù)型數(shù)據(jù),看偏度,一般大于0.75的數(shù)值做一個(gè)log轉(zhuǎn)化,使之盡量符合正態(tài)分布,因?yàn)楹芏嗄P偷募僭O(shè)數(shù)據(jù)是服從正態(tài)分布的 skewed_feats = data[cont_col].apply(lambda x: (x.dropna()).skew() )#compute skewness skewed_feats = skewed_feats[skewed_feats > 0.75] skewed_feats = skewed_feats.index data[skewed_feats] = np.log1p(data[skewed_feats]) skewed_feats
#對(duì)于連續(xù)型數(shù)據(jù),對(duì)其進(jìn)行標(biāo)準(zhǔn)化 scaled=preprocessing.scale(data[cont_col]) scaled=pd.DataFrame(scaled,columns=cont_col) scaled
m=dummies.join(scaled) data_cleaned=data[id_col].join(m) data_cleaned
看變量之間的相關(guān)性:
data_cleaned.corr()
#以下是相關(guān)性的熱力圖,方便肉眼看 def corr_heat(df): dfData = abs(df.corr()) plt.subplots(figsize=(9, 9)) # 設(shè)置畫面大小 sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Blues") # plt.savefig('./BluesStateRelation.png') plt.show() corr_heat(data_cleaned)
如果有覺(jué)得相關(guān)性偏高的視情況刪減某些變量。
#取出與某個(gè)變量(這里指能力)相關(guān)性最大的前四個(gè),做出熱點(diǎn)圖表示 k = 4 #number of variables for heatmap cols = corrmat.nlargest(k, '能力')['能力'].index cm = np.corrcoef(data_cleaned[cols].values.T) sns.set(font_scale=1.25) hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values) plt.show()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python使用正則表達(dá)式的search()函數(shù)實(shí)現(xiàn)指定位置搜索功能
SEARCH函數(shù),函數(shù)名。主要用來(lái)返回指定的字符串在原始字符串中首次出現(xiàn)的位置 ,從左到右查找,忽略英文字母的大小寫。接下來(lái)通過(guò)本文給大家介紹python使用正則表達(dá)式的search()函數(shù)實(shí)現(xiàn)指定位置搜索功能,需要的朋友一起看看吧2017-11-11導(dǎo)致python中import錯(cuò)誤的原因是什么
在本篇文章里小編給大家整理了關(guān)于python的import錯(cuò)誤原因以及相關(guān)內(nèi)容,需要的朋友們可以學(xué)習(xí)下。2020-07-07從零開(kāi)始搭建基于Python的微信小程序的教程分享
這篇文章主要為大家展示了如何從零開(kāi)始搭建一個(gè)基于?Python?的微信小程序項(xiàng)目,包含詳細(xì)的解決思路、方案和實(shí)際案例,希望對(duì)大家有所幫助2023-05-05使用Python的Flask框架構(gòu)建大型Web應(yīng)用程序的結(jié)構(gòu)示例
雖說(shuō)Flask是一個(gè)以輕量級(jí)著稱的框架,但也為大型Web應(yīng)用提供了諸如單元測(cè)試與數(shù)據(jù)庫(kù)遷移等許多便利的功能,這里我們來(lái)看一下使用Python的Flask框架構(gòu)建大型Web應(yīng)用程序的結(jié)構(gòu)示例:2016-06-06Python時(shí)間獲取及轉(zhuǎn)換知識(shí)匯總
這篇文章主要介紹了Python時(shí)間獲取及轉(zhuǎn)換知識(shí)匯總的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-01-01Python繪圖系統(tǒng)之繪制散點(diǎn)圖,極坐標(biāo)和子圖
這篇文章主要為大家詳細(xì)介紹了如何基于Python實(shí)現(xiàn)一個(gè)繪圖系統(tǒng),可以支持繪制散點(diǎn)圖,極坐標(biāo)和子圖,文中的示例代碼講解詳細(xì),感興趣的可以了解下2023-09-09