1. 程式人生 > >機器學習筆記(二):python 模組pandas

機器學習筆記(二):python 模組pandas

1.讀csv檔案資料

import pandas as pd
Info = pd.read_csv('titanic_train.csv');
#print(type(Info))   	#Info的型別 <class 'pandas.core.frame.DataFrame'>
#Info.dtypes           #得到每個欄位的型別  字串型別變為objec
#help(type)            檢視函式使用

Info.head(10)          #顯示前10行
Info.tail(2)              #顯示最後2行

#Info.shape      # 輸出  (樣本數(行數), 列數) 

2.對讀入的csv檔案資料 取值

Info['Name']   #得到這一列的資料
Info[['Name','Survived']]  #得到多列資料
Info['Name'][[1,2,3]]    #1,2,3行的Name資訊

Info.loc[2]    #得到第2個樣本的資料
Info.loc[2:6]   #得到 2-6
Info.loc[[2,5,7]]  #指定幾行樣本
Info.loc[88,"Name"]     #第88行的Name列資料
Info.loc[88:100,"Name"]     #第88-100的Name列資料
Info.loc[[88,100],"Name"]     #第88,和第100行的Name列資料
Info.loc[88:100,["Name","Survived"]]    #多列


print(Info['Fare'].max())    #這一列最大值
print(Info['Fare'].max()) 


#丟棄帶有NAN的所有項 通常情況下刪除行,使用引數axis = 0,刪除列的引數axis = 1,通常不會這麼做,那樣會刪除一個變數。
print(Info.dropna(axis=0));

Info.values   #得到一個值的 numpy.ndarray
Info.columns   #輸出每列的列名


3.排序,索引設定

#可選引數
#ascending  True降序, False升序
#axis = 0(預設)  就是按照列排序 ,此時第一個引數是列名
#axis = 1   按照行排序   此時第一個引數是行號
#inplace  是否替代原來的資料框
Info.sort_values("Fare",ascending=True,axis=0).head(2)

#drop為False 表示原來的索引列會被還原為普通列存起來,True則會把原來索引丟掉 , 預設False
Info.sort_values("Fare",ascending=True,axis=0).head(10).reset_index(drop=True)
#設定新索引
Info.sort_values("Fare",ascending=True,axis=0).head(10).set_index("Fare")


下面是找到以 d結尾的列名的值

#下面是找到以 d結尾的列名的值
cols = Info.columns.tolist()    #列 =》 lis
P = [];
for i in cols:
    if i.endswith('d'):
         P.append(i)       
Info[P]

如果每張票打6折是多少錢

#Info['Fare'] = Info['Fare']*0.6   注意,  =  的兩端緯度要相同(行數)

泰坦尼克遇難統計

#獲救者平均年齡

InfoS =Info.query("Survived == 1")
age_is_null  =  pd.isnull(InfoS['Age'])  #Age這一列 是否缺值的情況
Info_Age = InfoS['Age'][age_is_null == False];  #得到Age欄不為空的值
Info_Age.sum() / Info_Age.shape[0]    # 28.343689655172415
InfoS['Age'].mean()   #28.343689655172415  不去缺值也能得到一樣的答案,說明mean自動去缺值

#每個船艙的平均價格
Passenger_classes = [1,2,3];  #3個船艙
Info_P = Info['Pclass'] 
R = [];
for i in Passenger_classes:
    r = Info['Fare'][Info_P == i].mean()
    R.append(r);  
R

apply 自定義函式

#自定義函式
def func(col):
    a = col.loc[99];
    return a
#使用自定義的函式
h = Info.apply(func
Info.apply(func
#使用函式
import math  
Info["Fare"].apply(math.sqrt)


Series

#series 即 矩陣的一行,或者一列 from pandas import Series

n= Info[“Name”].shape[0]

#構造一個Series Series(值,索引) A = Series(Info[“Name”].head(3).values,[‘c’,‘a’,‘c’])

A[‘a’] A[[‘a’,‘b’]]

A.sort_values() #值排序 a-z升序

Index = sorted(A.index.tolist()) #對索引進行排序 A.reindex(Index) #根據新索引順序,對老資料排序(索引對應的值不變)