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...