對pandas進行數(shù)據(jù)預處理的實例講解
參加kaggle數(shù)據(jù)挖掘比賽,就第一個賽題Titanic的數(shù)據(jù),學習相關數(shù)據(jù)預處理以及模型建立,本博客關注基于pandas進行數(shù)據(jù)預處理過程。包括數(shù)據(jù)統(tǒng)計、數(shù)據(jù)離散化、數(shù)據(jù)關聯(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)計信息
數(shù)值屬性離散化
計算特征與target屬性之間關系
查看數(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)計信息
#查看連續(xù)數(shù)值屬性基本統(tǒng)計情況 print train_df.describe() #查看object屬性數(shù)據(jù)統(tǒng)計情況 print train_df.describe(include=['O']) # 統(tǒng)計Title單列各個元素對應的個數(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)造一個新列,F(xiàn)areBand,將連續(xù)屬性Fare切分成四份
train_df['FareBand'] = pd.qcut(train_df['Fare'], 4)
# 查看切分后的屬性與target屬性Survive的關系
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)
計算特征與target屬性之間關系
object與連續(xù)target屬性之間,可以groupby均值
object與離散target屬性之間,先將target數(shù)值化,然后groupby均值,或者分別條形統(tǒng)計圖
連續(xù)屬性需要先切割然后再進行groupby計算,或者pearson相關系數(shù)
print train_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False).mean().sort_values(by='AgeBand', ascending=True)
總結pandas基本操作
”'
創(chuàng)建df對象
””'
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() #對每列數(shù)據(jù)進行初步的統(tǒng)計
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]] #通過index來訪問
print df3.loc[df3.index[0],['col2']] #通過行index,和列名來唯一確定一個位置
print df3.iloc[1] #通過位置來訪問
print df3.iloc[[1,2],1:2] #通過位置來訪問
print "==="
print df3.loc[:,['col1','col2']].as_matrix() # 返回nunpy二元數(shù)組
print type(df3.loc[:,['col1','col2']].as_matrix())
'''
4.布爾索引,過濾數(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的列
以上這篇對pandas進行數(shù)據(jù)預處理的實例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解用pyecharts Geo實現(xiàn)動態(tài)數(shù)據(jù)熱力圖城市找不到問題解決
這篇文章主要介紹了詳解用pyecharts Geo實現(xiàn)動態(tài)數(shù)據(jù)熱力圖城市找不到問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-06-06

