NumPy

Python 入門

Hugo Bowne-Anderson

Data Scientist at DataCamp

串列回顧

  • 功能強大

  • 數值的集合

  • 儲存不同類型的資料

  • 更改、新增、刪除

  • 資料科學的需求

    • 集合上的數學運算

    • 速度

Python 入門

示意圖

height = [1.73, 1.68, 1.71, 1.89, 1.79]
height
[1.73, 1.68, 1.71, 1.89, 1.79]
weight = [65.4, 59.2, 63.6, 88.4, 68.7]
weight
[65.4, 59.2, 63.6, 88.4, 68.7]
weight / height ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
Python 入門

解決方案: NumPy

  • Numeric Python

  • Python 串列的替代方案: NumPy 陣列

  • 計算整個陣列

  • 簡單快捷

  • 安裝

    • 在終端中:pip3 install numpy
Python 入門

NumPy

import numpy as np

np_height = np.array(height) np_height
array([1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = np.array(weight)
np_weight
array([65.4, 59.2, 63.6, 88.4, 68.7])
bmi = np_weight / np_height ** 2
bmi
array([21.85171573, 20.97505669, 21.75028214, 24.7473475 , 21.44127836])
Python 入門

對比

height = [1.73, 1.68, 1.71, 1.89, 1.79]
weight = [65.4, 59.2, 63.6, 88.4, 68.7]
weight / height ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
np_height = np.array(height)
np_weight = np.array(weight)
np_weight / np_height ** 2
array([21.85171573, 20.97505669, 21.75028214, 24.7473475 , 21.44127836])
Python 入門

NumPy:注意事項

np.array([1.0, "is", True])
array(['1.0', 'is', 'True'], dtype='<U32')
  • NumPy 陣列:僅包含一種型別
Python 入門

NumPy:注意事項

python_list = [1, 2, 3]
numpy_array = np.array([1, 2, 3])
python_list + python_list
[1, 2, 3, 1, 2, 3]
numpy_array + numpy_array
array([2, 4, 6])
  • 不同型別:行為也不同!
Python 入門

NumPy 子集化

bmi
array([21.85171573, 20.97505669, 21.75028214, 24.7473475 , 21.44127836])
bmi[1]
20.975
bmi > 23
array([False, False, False,  True, False])
bmi[bmi > 23]
array([24.7473475])
Python 入門

一起來練習吧!

Python 入門

Preparing Video For Download...