pandas

首先導入相關模塊並加載數據集到 Python 環境中:python

import pandas as pd
import numpy as np
data = pd.read_csv("train.csv", index_col="Loan_ID")git

#1 – 布爾索引

若是須要以其它列數據值爲條件過濾某一列的數據,您會怎麼處理?例如創建一個列表,列表中所有爲未能畢業但曾得到貸款的女性。這裏可使用布爾索引,代碼以下:github

 

1.-boolean-indexing

#2 – Apply 函數

Apply 函數是處理數據和創建新變量的經常使用函數之一。在向數據框的每一行或每一列傳遞指定函數後,Apply 函數會返回相應的值。這個由 Apply 傳入的函數能夠是系統默認的或者用戶自定義的。例如,在下面的例子中它能夠用於查找每一行和每一列中的缺失值。算法

#Create a new function:
def num_missing(x):
return sum(x.isnull())數組

#Applying per column:
print "Missing values per column:"
print data.apply(num_missing, axis=0) #axis=0 defines that function is to be applied on each columnapp

#Applying per row:
print "nMissing values per row:"
print data.apply(num_missing, axis=1).head() #axis=1 defines that function is to be applied on each row框架

這樣咱們就獲得了所需的結果。ide

注:因爲輸出結果包含多行數據,第二個輸出函數使用了 head() 函數以限定輸出數據長度。在不限定輸入參數時 head() 函數默認輸出 5 行數據。函數

#3 – 填補缺失值

fillna() 函數可一次性完成填補功能。它能夠利用所在列的均值/衆數/中位數來替換該列的缺失數據。下面利用「Gender」、「Married」、和「Self_Employed」列中各自的衆數值填補對應列的缺失數據。測試

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息