NumPy 陣列的威力

撰寫高效的 Python 程式碼

Logan Thomas

Scientific Software Technical Trainer, Enthought

NumPy 陣列概觀

  • Python 清單的替代方案
nums_list = list(range(5))
[0, 1, 2, 3, 4]
import numpy as np

nums_np = np.array(range(5))
array([0, 1, 2, 3, 4])
撰寫高效的 Python 程式碼
# NumPy 陣列的同質性
nums_np_ints = np.array([1, 2, 3])
array([1, 2, 3])
nums_np_ints.dtype
dtype('int64')
nums_np_floats = np.array([1, 2.5, 3])
array([1. , 2.5, 3. ])
nums_np_floats.dtype
dtype('float64')
撰寫高效的 Python 程式碼

NumPy 陣列的廣播

  • Python 清單不支援廣播
nums = [-2, -1, 0, 1, 2]
nums ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
撰寫高效的 Python 程式碼
  • 清單作法
# for 迴圈(效能較差)
sqrd_nums = []
for num in nums:
    sqrd_nums.append(num ** 2)
print(sqrd_nums)
[4, 1, 0, 1, 4]
# 串列生成式(較好但不是最佳)
sqrd_nums  = [num ** 2 for num in nums]

print(sqrd_nums)
[4, 1, 0, 1, 4]
撰寫高效的 Python 程式碼

NumPy 陣列的廣播

  • 使用 NumPy 廣播更簡潔!
nums_np = np.array([-2, -1, 0, 1, 2])
nums_np ** 2
array([4, 1, 0, 1, 4])
撰寫高效的 Python 程式碼

基礎一維索引(清單)

nums = [-2, -1, 0, 1, 2]
nums[2]
0
nums[-1]
2
nums[1:4]
[-1, 0, 1]

基礎一維索引(陣列)

nums_np = np.array(nums)
nums_np[2]
0
nums_np[-1]
2
nums_np[1:4]
array([-1, 0, 1])
撰寫高效的 Python 程式碼
# 二維清單
nums2 = [ [1, 2, 3],
          [4, 5, 6] ]

  • 基礎二維索引(清單)
nums2[0][1]
2
[row[0] for row in nums2]
[1, 4]
# 二維陣列

nums2_np = np.array(nums2)

  • 基礎二維索引(陣列)
nums2_np[0,1]
2
nums2_np[:,0]
array([1, 4])
撰寫高效的 Python 程式碼

NumPy 陣列的布林索引

nums = [-2, -1, 0, 1, 2]
nums_np =  np.array(nums)
  • 布林索引
nums_np > 0
array([False, False, False,  True,  True])
nums_np[nums_np > 0]
array([1, 2])
撰寫高效的 Python 程式碼
  • 清單不支援布林索引
# for 迴圈(效能較差)
pos = []
for num in nums:
    if num > 0:
        pos.append(num)
print(pos)
[1, 2]
# 串列生成式(較好但不是最佳)
pos = [num for num in nums if num > 0]
print(pos)
[1, 2]
撰寫高效的 Python 程式碼

一起來練習吧!強大的 NumPy 陣列

撰寫高效的 Python 程式碼

Preparing Video For Download...