【Data Mining】機器學習三劍客之Pandas常用用法總結(上)
- 2019 年 12 月 9 日
- 筆記
一、前言
看pandas之前我建議先看我的numpy總結,效果更佳。 【Data Mining】機器學習三劍客之Numpy常用用法總結 可以大概理解為numpy主要是用來生成數據,並且進行數據運算的工具 而pandas主要是用來整個數據的管理,也就是整個數據的擺放或是一些行列的操作等等。當然也不完全是這個樣子。
二、下載、安裝、導入
用anaconda安裝是十分方便的,如果你已經安裝了tf,keras之類的,其實已經直接把numpy安裝了,一般來說安裝就是pip命令。
pip install pandas #py2 pip3 install pandas #py3
用法則是
import pandas as pd # 一般as為pd來操作
三、常用用法總結
1.Series
# -*- coding: utf-8 -*- import pandas as pd import numpy as np df1 = pd.DataFrame(np.arange(12).reshape((3, 4))) print df1 """ 0 1 2 3 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 """ s = pd.Series([1, 1, 44, 22]) #創建一個series s_type_int_float = pd.Series([1, 1, 44, 22], dtype=np.float32) #更改type s_type = pd.Series([1, np.nan, 44, 22]) #np.nan就是就是Nan預設值 16 #更改index s_index = pd.Series([1, np.nan, 44, 22], index=["c", "h", "e", "hongshu"]) print("s:") print(s) print("s_type_int_float:") print(s_type_int_float) print("s_type:") print(s_type) print("s_index:") print(s_index) """ s: 0 1 1 1 2 44 3 22 dtype: int64 s_type_int_float: 0 1.0 1 1.0 2 44.0 3 22.0 dtype: float32 s_type: 0 1.0 1 NaN 2 44.0 3 22.0 dtype: float64 s_index: c 1.0 h NaN e 44.0 hongshu 22.0 dtype: float64 """
一些說明:
- series相當於dataframe的一個元素,pandas的主體數據類型為dataframe,一個series單位相當於dataframe的一行,當然是連帶這整個dataframe的column和元素dtype的資訊的。(ps:這裡可以先記著,後面慢慢才能全都懂,先記住這麼個關係,後面講)
- 生成series的左面一列其實就是dataframe的每一列的index,例如上述s左面為[0, 1, 2, 3]其實就是和我上面寫的那個dataframe的最上面的單獨的一行對應,代表每一列的名字,有點像excel表格中的每一列的name。
- 上述採用list生成的series,理論上用array-like的形式都可以生成,當然numpy毋庸置疑可以後面會有展示,如果生成的series的list中的每個元素為整型,則dtype默認推理為int64,如果元素中海包括nan預設值則按浮點數處理,所以默認為float64,可知如果都為浮點數則默認為float64。
- 如果要是自定義dtype和往常一樣自然轉換,整數化或者浮點化。
# -*- coding: utf-8 -*- import pandas as pd import numpy as np s_np1 = pd.Series(np.arange(6)) #利用numpy生成series的方法 data_numpy = np.array([1, 2, 3, 45], dtype=np.float32) s_np2 = pd.Series(data_numpy) data_numpy1 = np.array([1, 2, 3, 45], dtype=np.int8) s_np3 = pd.Series(data_numpy1) data_numpy2 = np.array([1, 2, 3, 45]) s_np4 = pd.Series(data_numpy2) print(s_np1) print(s_np2) print(s_np3) print(s_np4) """ 0 0 1 1 2 2 3 3 4 4 5 5 dtype: int64 0 1.0 1 2.0 2 3.0 3 45.0 dtype: float32 0 1 1 2 2 3 3 45 dtype: int8 0 1 1 2 2 3 3 45 dtype: int64 """
上面這個主要看dtype,可知規律為通過numpy生成series時dtype跟隨numpy的類型。
2、 DataFrame
①、df的index和colomns操作
# -*- coding: utf-8 -*- import pandas as pd import numpy as np # 通過numpy生成隨機0-10的shape為(3, 4)的dataframe df_np = pd.DataFrame(np.random.randint(low=0, high=10, size=(3, 4))) print(df_np) # 生成隨機-1-1的dataframe # 更改index df_index = pd.DataFrame(np.random.randn(3, 4), index=['f', 's', 't']) print(df_index) # 更改column df_colums = pd.DataFrame(np.arange(12).reshape((3, 4)), columns=['che', 'hong', 'shu', '24']) print(df_colums) """ 0 1 2 3 0 2 3 0 3 1 7 0 5 8 2 0 5 2 7 0 1 2 3 f -2.216776 -1.506733 0.870351 1.361973 s 1.104645 -1.538397 -0.616963 -2.101459 t -1.423237 -0.378047 -0.294814 -0.200800 che hong shu 24 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 """ #use dict to create dataframe dates_value = pd.date_range('20181222', periods=3) #dict的key對應於df的colomn df_dict = pd.DataFrame({'che': 22.22, 'hong': pd.Series(np.array([1, 2, 3], dtype=np.float32)), 'shu': dates_value}) print(df_dict) """ che hong shu 0 22.22 1.0 2018-12-22 1 22.22 2.0 2018-12-23 2 22.22 3.0 2018-12-24
這裡需要注意的一點:dataframe中的colomn參數其實就是series中的index。
總結一下:
- dataframe可以通過dict和numpy生成
- 主要設置參數為index和colomns, index為每行的名稱,colomns為每列的,對應於每一行的series的index。
- 利用dict生成dataframe時,dict的keys對應於dataframe的colomns
②、df的各種屬性
import pandas as pd import numpy as np # pandas.Categorical #https://blog.csdn.net/weixin_38656890/article/details/81348539 df2 = pd.DataFrame({'A': 1., 'B': pd.Timestamp('20130102'), 'C': pd.Series(1, index=list(range(4)), dtype='float32'), 'D': np.array([3, 6, 9, 12], dtype=np.int32), 'E': pd.Categorical(["test", "train", "test", "train"]), 'F': 'che'}) print(df2) print(df2.dtypes) #return the data type of each column. """ A B C D E F 0 1.0 2013-01-02 1.0 3 test che 1 1.0 2013-01-02 1.0 6 train che 2 1.0 2013-01-02 1.0 9 test che 3 1.0 2013-01-02 1.0 12 train che A float64 B datetime64[ns] C float32 D int32 E category F object """ print(df2.index) print(df2.columns) """ Int64Index([0, 1, 2, 3], dtype='int64') Index([u'A', u'B', u'C', u'D', u'E', u'F'], dtype='object') """ print(df2.values) # 返回數據類型為numpy可知取出元素其中一個方法是變成list之後取出即可 # 當然這個方法速度慢,有更好的內置取值的方法 print(type(df2.values)) """ [[1.0 Timestamp('2013-01-02 00:00:00') 1.0 3 'test' 'che'] [1.0 Timestamp('2013-01-02 00:00:00') 1.0 6 'train' 'che'] [1.0 Timestamp('2013-01-02 00:00:00') 1.0 9 'test' 'che'] [1.0 Timestamp('2013-01-02 00:00:00') 1.0 12 'train' 'che']] <type 'numpy.ndarray'> """ # 數字類data的各種數學計算結果 # 數量、平均、標準差、最小等 print(df2.describe()) """ A C D count 4.0 4.0 4.000000 mean 1.0 1.0 7.500000 std 0.0 0.0 3.872983 min 1.0 1.0 3.000000 25% 1.0 1.0 5.250000 50% 1.0 1.0 7.500000 75% 1.0 1.0 9.750000 max 1.0 1.0 12.000000 """ """ 原dataframe 方便對比觀看 A B C D E F 0 1.0 2013-01-02 1.0 3 test che 1 1.0 2013-01-02 1.0 6 train che 2 1.0 2013-01-02 1.0 9 test che 3 1.0 2013-01-02 1.0 12 train che """ print(df2.T) #轉置 """ 0 ... 3 A 1 ... 1 B 2013-01-02 00:00:00 ... 2013-01-02 00:00:00 C 1 ... 1 D 3 ... 12 E test ... train F che ... che """ print(df2.sort_index(axis=1, ascending=False)) # axis=1 相當於colomn元素排序 print(df2.sort_index(axis=0, ascending=False)) # axis=0 相當於index排序 # 其他value順著index或者colomns排序即可 """ F E D C B A 0 che test 3 1.0 2013-01-02 1.0 1 che train 6 1.0 2013-01-02 1.0 2 che test 9 1.0 2013-01-02 1.0 3 che train 12 1.0 2013-01-02 1.0 A B C D E F 3 1.0 2013-01-02 1.0 12 train che 2 1.0 2013-01-02 1.0 9 test che 1 1.0 2013-01-02 1.0 6 train che 0 1.0 2013-01-02 1.0 3 test che """ print(df2.sort_values(by='E')) #通過colomn為E的單位的value來排序(如果是數字則按數字大小排列,字母按字母大小) """ A B C D E F 0 1.0 2013-01-02 1.0 3 test che 2 1.0 2013-01-02 1.0 9 test che 1 1.0 2013-01-02 1.0 6 train che 3 1.0 2013-01-02 1.0 12 train che """
3、select
# -*- coding: utf-8 -*- import pandas as pd import numpy as np dates = pd.date_range('20121222', periods=6) df = pd.DataFrame(np.arange(24).reshape((6, 4)), index=dates, columns=['A', 'B', 'C', 'D']) #easy selection print(df) """ A B C D 2012-12-22 0 1 2 3 2012-12-23 4 5 6 7 2012-12-24 8 9 10 11 2012-12-25 12 13 14 15 2012-12-26 16 17 18 19 2012-12-27 20 21 22 23 """ # select 'A' colomn print(df['A']) print(df.A) """ 2012-12-22 0 2012-12-23 4 2012-12-24 8 2012-12-25 12 2012-12-26 16 2012-12-27 20 Freq: D, Name: A, dtype: int64 2012-12-22 0 2012-12-23 4 2012-12-24 8 2012-12-25 12 2012-12-26 16 2012-12-27 20 Freq: D, Name: A, dtype: int64 """ # select 0-3 rows print(df[0: 3]) print(df['2012-12-22':'2012-12-24']) """ A B C D 2012-12-22 0 1 2 3 2012-12-23 4 5 6 7 2012-12-24 8 9 10 11 A B C D 2012-12-22 0 1 2 3 2012-12-23 4 5 6 7 2012-12-24 8 9 10 11 """ """ 原dataframe, 適宜對比觀看 A B C D 2012-12-22 0 1 2 3 2012-12-23 4 5 6 7 2012-12-24 8 9 10 11 2012-12-25 12 13 14 15 2012-12-26 16 17 18 19 2012-12-27 20 21 22 23 """ # select by label= loc # 這裡的label其實就是我之前說dataframe對應的colomn和index # 和平時的二維的numpy選取相似,只是把index轉換為對應的label name print(df.loc['20121224']) #loc[]內單個一個label name時為行的index name print(df.loc[:, 'A':'C']) # : 代表所有的行都要 逗號後面為colomns的label name """ A 8 B 9 C 10 D 11 Name: 2012-12-24 00:00:00, dtype: int64 A B C 2012-12-22 0 1 2 2012-12-23 4 5 6 2012-12-24 8 9 10 2012-12-25 12 13 14 2012-12-26 16 17 18 2012-12-27 20 21 22 """ print(df.loc[:, ['A', 'C']]) print(df.loc['20121223', ['A', 'C']]) """ A C 2012-12-22 0 2 2012-12-23 4 6 2012-12-24 8 10 2012-12-25 12 14 2012-12-26 16 18 2012-12-27 20 22 A 4 C 6 Name: 2012-12-23 00:00:00, dtype: int64 """ """ 原dataframe, 適宜對比觀看 A B C D 2012-12-22 0 1 2 3 2012-12-23 4 5 6 7 2012-12-24 8 9 10 11 2012-12-25 12 13 14 15 2012-12-26 16 17 18 19 2012-12-27 20 21 22 23 """ # select by position(index)= iloc # 這裡的selection index其實就是完全和numpy相似 # (row index, colomn index) # 利用行的索引和列的索引來取值 print(df.iloc[3]) print(df.iloc[3:5, 1:3]) print(df.iloc[[1, 3], 1:3]) """ A 12 B 13 C 14 D 15 Name: 2012-12-25 00:00:00, dtype: int64 B C 2012-12-25 13 14 2012-12-26 17 18 B C 2012-12-23 5 6 2012-12-25 13 14 """ # mixed selection = ix # label + position selection print(df.ix[1, ['A', 'D']]) """ A 4 D 7 Name: 2012-12-23 00:00:00, dtype: int64 """ # Boolean indexing # use bool to select print(df[df.B > 9]) """ A B C D 2012-12-25 12 13 14 15 2012-12-26 16 17 18 19 2012-12-27 20 21 22 23 """
一些總結:
- 一種選擇數據有五種:簡單直接選取,label選取(loc),index選取(iloc),混合選取(ix),真假選取
- 其實第二種到第四種選取,有規律可言,其實都是[row,colomn]的組合而已,只是一個是用label name,一個是index name,混合是label or index
- 第一種其實就是label或者index的單列或者行選取,但是也有特殊表達比如df.A
- 最後一種主要用於刪選數據的。
4、讀取文件,輸出文件
在使用中主要針對於excel文件和csv文件,個人推薦csv文件,因為在很多比賽和項目中都採用此類型,主要是兼容性好一些,我在linux下使用excel問題很多,當然對於pandas兩樣的使用很相似。 首先我們採用常用的機器學習數據集:iris數據集,鏈接如下

數據集簡單介紹:鳶尾花的特徵作為數據來源,數據集包含150個數據集,分為3類,每類50個數據,每個數據包含4個屬性,數據集iris.csv截圖如下。

數據集內容 此處進行簡單讀入,並按照演算法輸入進行簡單處理,並輸出
import pandas as pd import numpy as np # 讀csv文件 Iris_dataset = pd.read_csv("./Iris_dataset/iris.csv") # 給每列一個column label Iris_dataset.columns = ['data_index', 'sepal_len', 'sepal_width', 'petal_len', 'petal_width', 'class'] # drop掉第一列(無用的列,表示數據index) Iris_dataset.drop(columns='data_index', axis=1, inplace=True) # 判斷是否存在nan if np.any(Iris_dataset.isnull()) == True: print("有空缺值") Iris_dataset.dropna() else: print("無空缺值") # 進行把string label name轉換為int型 def fun(x): if x == 'setosa': return 0 elif x == 'versicolor': return 1 elif x == 'virginica': return 2 Iris_dataset['class'] = Iris_dataset['class'].apply(lambda x: fun(x)) # 前五條數據 print(Iris_dataset.head()) # 輸出.csv文件 Iris_dataset.to_csv('iris_handle_data')
輸出文件如下:

輸出結果 主要輸出輸入,我建議使用.csv數據,若使用excel文件函數如下
p = pd.read_excel() p.to_excel()