您好,登錄后才能下訂單哦!
參加kaggle數(shù)據(jù)挖掘比賽,就第一個(gè)賽題Titanic的數(shù)據(jù),學(xué)習(xí)相關(guān)數(shù)據(jù)預(yù)處理以及模型建立,本博客關(guān)注基于pandas進(jìn)行數(shù)據(jù)預(yù)處理過(guò)程。包括數(shù)據(jù)統(tǒng)計(jì)、數(shù)據(jù)離散化、數(shù)據(jù)關(guān)聯(lián)性分析
引入包和加載數(shù)據(jù)
import pandas as pd import numpy as np train_df =pd.read_csv('../datas/train.csv') # train set test_df = pd.read_csv('../datas/test.csv') # test set combine = [train_df, test_df]
清洗數(shù)據(jù)
查看數(shù)據(jù)維度以及類型
缺失值處理
查看object數(shù)據(jù)統(tǒng)計(jì)信息
數(shù)值屬性離散化
計(jì)算特征與target屬性之間關(guān)系
查看數(shù)據(jù)維度以及類型
#查看前五條數(shù)據(jù) print train_df.head(5) #查看每列數(shù)據(jù)類型以及nan情況 print train_df.info() # 獲得所有object屬性 print train_data.describe(include=['O']).columns
查看object數(shù)據(jù)統(tǒng)計(jì)信息
#查看連續(xù)數(shù)值屬性基本統(tǒng)計(jì)情況 print train_df.describe() #查看object屬性數(shù)據(jù)統(tǒng)計(jì)情況 print train_df.describe(include=['O']) # 統(tǒng)計(jì)Title單列各個(gè)元素對(duì)應(yīng)的個(gè)數(shù) print train_df['Title'].value_counts() # 屬性列刪除 train_df = train_df.drop(['Name', 'PassengerId'], axis=1)
缺失值處理
# 直接丟棄缺失數(shù)據(jù)列的行 print df4.dropna(axis=0,subset=['col1']) # 丟棄nan的行,subset指定查看哪幾列 print df4.dropna(axis=1) # 丟棄nan的列 # 采用其他值填充 dataset['Cabin'] = dataset['Cabin'].fillna('U') dataset['Title'] = dataset['Title'].fillna(0) # 采用出現(xiàn)最頻繁的值填充 freq_port = train_df.Embarked.dropna().mode()[0] dataset['Embarked'] = dataset['Embarked'].fillna(freq_port) # 采用中位數(shù)或者平均數(shù)填充 test_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True) test_df['Fare'].fillna(test_df['Fare'].dropna().mean(), inplace=True)
數(shù)值屬性離散化,object屬性數(shù)值化
# 創(chuàng)造一個(gè)新列,F(xiàn)areBand,將連續(xù)屬性Fare切分成四份 train_df['FareBand'] = pd.qcut(train_df['Fare'], 4) # 查看切分后的屬性與target屬性Survive的關(guān)系 train_df[['FareBand', 'Survived']].groupby(['FareBand'], as_index=False).mean().sort_values(by='FareBand', ascending=True) # 建立object屬性映射字典 title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Royalty":5, "Officer": 6} dataset['Title'] = dataset['Title'].map(title_mapping)
計(jì)算特征與target屬性之間關(guān)系
object與連續(xù)target屬性之間,可以groupby均值
object與離散target屬性之間,先將target數(shù)值化,然后groupby均值,或者分別條形統(tǒng)計(jì)圖
連續(xù)屬性需要先切割然后再進(jìn)行g(shù)roupby計(jì)算,或者pearson相關(guān)系數(shù)
print train_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False).mean().sort_values(by='AgeBand', ascending=True)
總結(jié)pandas基本操作
”' 創(chuàng)建df對(duì)象 ””' s1 = pd.Series([1,2,3,np.nan,4,5]) s2 = pd.Series([np.nan,1,2,3,4,5]) print s1 dates = pd.date_range(“20130101”,periods=6) print dates df = pd.DataFrame(np.random.rand(6,4),index=dates,columns=list(“ABCD”)) # print df df2 = pd.DataFrame({“A”:1, ‘B':pd.Timestamp(‘20130102'), ‘C':pd.Series(1,index=list(range(4)),dtype='float32'), ‘D':np.array([3]*4,dtype=np.int32), ‘E':pd.Categorical([‘test','train','test','train']), ‘F':'foo' }) # print df2.dtypes
df3 = pd.DataFrame({'col1':s1, 'col2':s2 }) print df3 ''' 2.查看df數(shù)據(jù) ''' print df3.head(2) #查看頭幾條 print df3.tail(3) #查看尾幾條 print df.index #查看索引 print df.info() #查看非non數(shù)據(jù)條數(shù) print type(df.values) #返回二元數(shù)組 # print df3.values print df.describe() #對(duì)每列數(shù)據(jù)進(jìn)行初步的統(tǒng)計(jì) print df3 print df3.sort_values(by=['col1'],axis=0,ascending=True) #按照哪幾列排序 ''' 3.選擇數(shù)據(jù) ''' ser_1 = df3['col1'] print type(ser_1) #pandas.core.series.Series print df3[0:2] #前三行 print df3.loc[df3.index[0]] #通過(guò)index來(lái)訪問(wèn) print df3.loc[df3.index[0],['col2']] #通過(guò)行index,和列名來(lái)唯一確定一個(gè)位置 print df3.iloc[1] #通過(guò)位置來(lái)訪問(wèn) print df3.iloc[[1,2],1:2] #通過(guò)位置來(lái)訪問(wèn) print "===" print df3.loc[:,['col1','col2']].as_matrix() # 返回nunpy二元數(shù)組 print type(df3.loc[:,['col1','col2']].as_matrix()) ''' 4.布爾索引,過(guò)濾數(shù)據(jù) ''' print df3[df3.col1 >2] df4 = df3.copy() df4['col3']=pd.Series(['one','two','two','three','one','two']) print df4 print df4[df4['col3'].isin(['one','two'])] df4.loc[:,'col3']="five" print df4 ''' 5.缺失值處理,pandas將缺失值用nan代替 ''' print pd.isnull(df4) print df4.dropna(axis=0,subset=['col1']) # 丟棄nan的行,subset指定查看哪幾列 print df4.dropna(axis=1) # 丟棄nan的列
以上這篇對(duì)pandas進(jìn)行數(shù)據(jù)預(yù)處理的實(shí)例講解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。