【NCCU DA 3.0 社課四|Python Pandas 教學】
在第一堂 Python 系列課程中,政大數據分析社邀請到在 Youtube 提供 Python 課程教學的講師彭彭,帶領社員們認識 Python 的基礎語法。延續上次的課程,本次講師彭彭以 Pandas 套件為課程重點,教導大家如何入門並實際應用。
為什麼要學習 Python Pandas?
Pandas 擁有強大的數據組織化、數據清理以及數學運算功能,且操作直觀易於上手 ,是進行資料處理與轉換的強力輔佐工具。因此,Pandas 是分析師們最常用的套件之一,也是初學者學習數據分析的必經之路。
以下內容將著重介紹 Pandas 中的「Series」以及「DataFrame」兩大基本概念。
Series 單維度資料
Pandas Series 是單維度的資料結構,可以把它想像成 Excel 中的一欄(column),可以儲存整數、浮點數、字串等不同型態的資料。
- 建立 Series 語法
首先,用 pandas.Series() 建立一個名為「numberData」的 Series,裡面有「3、4、10、2、5、100」6筆資料。
import pandas as pd
print("根據列表建立 Series")
numberData=pd.Series([3,4,10,2,5,100])
print(numberData)
觀察剛建立的Series — — numberData,左側一欄為索引(index),右側一欄則為值(value),一個索引對應一個值。
根據列表建立 Series
0 3
1 4
2 10
3 2
4 5
5 100
dtype: int64
- 資料型態觀察
透過 dtype() 以及 size() 的語法觀察,可以發現 numberData 的資料一共有6筆,型態為「整數」
print("Series 的資料型態", numberData.dtype)
print("Series 的資料數量", numberData.size)
Series 的資料型態 int64
Series 的資料數量 6
- 數字的基本運算
對 Series 進行四則運算時,相當於對其中的每一個數值分別進行運算。簡單的操作便可以完成所有的運算,是 Pandas 的一大優點。以下為加法及乘法的範例:
print("做加法", numberData+10)
print("做乘法", numberData*2)
做加法 0 13
1 14
2 20
3 12
4 15
5 110
dtype: int64
做乘法 0 6
1 8
2 20
3 4
4 10
5 200
dtype: int64
- 數字的統計資訊
Pandas 不僅能靈活地對數據進行運算,也非常適合用於統計分析。例如:利用 <、>、= 等條件設定了解數據的分佈。此時,numberData 的資料型態會轉變成「布林值」。
print("做大於小於等於比較")
print(numberData>5)
做大於小於等於比較
0 False
1 False
2 True
3 False
4 False
5 True
dtype: bool
除了基本的大小比較, Pandas 更支援 max()、min()、mean()、median() 等各項功能,能幫助我們快速獲得 numberData 的統計資訊。
print("找到最大值", numberData.max())
print("統計平均數", numberData.mean())
找到最大值 100
統計平均數 20.666666666666668
- 字串的運算
Series 不僅能儲存數字,也能儲存字串,並針對字串進行各項處理。
用 pandas.Series() 建立一個名為「strData」的 Series,裡面有「Amy、Bob、John」3筆資料。此時,strData 的資料型態為「物件」。
strData=pd.Series(["Amy", "Bob", "John"])
print(strData)
0 Amy
1 Bob
2 John
dtype: object
Pandas 中的 upper() 、lower() 函數可以轉換字串的大小寫;contains() 函數則可以檢查字串中是否包含特定關鍵字,結果以「布林值」呈現。
print("轉換成全大寫", strData.str.upper())
print("檢查關鍵字", strData.str.contains("o"))
轉換成全大寫 0 AMY
1 BOB
2 JOHN
dtype: object
檢查關鍵字 0 False
1 True
2 True
dtype: bool
DataFrame 多維度資料
Pandas DataFrame 是多維度的資料結構,類似於 Excel 中的表格,同時包含欄(column)與列(row)。和 Series 一樣支援多種資料型態,經常應用於讀取CSV檔案及資料庫。
- 建立 DataFrame 語法
結合上一堂課學習到的字典(Dictionary),利用 pandas.DataFrame() 建立一個名為「employeeData」的 DataFrame。
import pandas as pd
print("根據字典建立 DataFrame")
employeeData=pd.DataFrame({
"name":["澎澎", "丁滿", "辛巴"],
"salary":[30000, 60000, 45000]
})
print(employeeData)
觀察剛建立的 DataFrame — — employeeData,最左側一欄為索引(index),右側二欄則為值(value),一個索引對應多個值。
根據字典建立 DataFrame
name salary
0 澎澎 30000
1 丁滿 60000
2 辛巴 45000
- 資料型態觀察
透過 size() 以及 shape() 的語法觀察,可以發現 employeeData 的資料呈現3列2行,一共有6筆。
print("資料的數量", employeeData.size)
print("資料的形狀", employeeData.shape)
資料的數量 6
資料的形狀 (3, 2)
- 取得特定欄位
當我們想取得 DataFrame 中的特定欄(Column)時,可以利用字典的語法;想取得特定列(row)時則可以使用 iloc() 函數。將兩者結合使用可以精準的鎖定某一筆資料。
print("取得 name 欄位")
print(employeeData["name"])
print("取得第 2 列")
print(employeeData.iloc[1])
print("取得第 2 列中的 salary 欄位")
print(employeeData.iloc[1]["salary"])
取得 name 欄位
0 澎澎
1 丁滿
2 辛巴
Name: name, dtype: object
取得第 2 列
name 丁滿
salary 60000
Name: 1, dtype: object
取得第 2 列中的 salary 欄位
60000
- 建立新的欄位
不管是直接建立新欄位,或者是根據現有欄位建立新欄位,都可以利用字典的語法完成。
print("建立新的欄位 admin,用布林值代表誰是主管")
employeeData["admin"]=[True, False, False]
print(employeeData)
print("根據現有欄位建立新的欄位 bonus,薪水的一成")
employeeData["bonus"]=employeeData["salary"]*0.1
print(employeeData)
建立新的欄位 admin,用布林值代表誰是主管
name salary admin
0 澎澎 30000 True
1 丁滿 60000 False
2 辛巴 45000 False
根據現有欄位建立新的欄位 bonus,薪水的一成
name salary admin bonus
0 澎澎 30000 True 3000.0
1 丁滿 60000 False 6000.0
2 辛巴 45000 False 4500.0
- 篩選資料
利用「 <、>、= 」、「True、False」等條件設定,即可快速篩選出所需的資料。
print("篩選出薪資小於 50000 的資料")
print(employeeData[employeeData["salary"]<50000])
篩選出薪資小於 50000 的資料
name salary admin bonus
0 澎澎 30000 True 3000.0
2 辛巴 45000 False 4500.0
本次的課程內容是 Pandas 的基礎教學,概念並不複雜,卻是數據分析不可或缺的技能。
想要建立扎實的 Pandas 基礎,除了不斷從實作中累積經驗,彭彭也鼓勵社員們從 Pandas 官方文件 中學習。官方文件雖然理解門檻較高,但擁有最齊全的內容,有助於建立完整的學習架構。
最後,政大數據分析社將在第三堂 Python 系列課程當中,介紹資料視覺化的邏輯與技巧。請社員們務必熟悉前兩堂課所學,以順利銜接課程!
延伸學習傳送門