一般来说,您希望避免(可能很慢)基于 python 的循环并让 numpy 执行(更快)基于 c 的循环(或根本不循环)。
大多数人会将删除显式循环的方法称为(numpy-)向量化,如果要提高性能,这通常非常重要。
以下示例创建 5 个大小为 (3,3) 的 numpy-arrays(矩阵类型,也存在,有点不推荐使用,此处未使用,大多数 numpy 用户应该使用数组作为矩阵的替换)并计算包含所有具有相同形状的平均值的新矩阵(矩阵单元上的元素均值;我们将二维数组解释为矩阵)。
代码:
import numpy as np
a, b, c, d, e = [np.random.randint(0, 5, size=(3,3)) for i in range(5)]
all = np.stack((a, b, c, d, e), axis=0)
print(all.shape)
x = np.mean(all, axis=0)
print(a)
print(b)
print(c)
print(d)
print(e)
print(x)
输出:
(5, 3, 3)
[[0 0 0]
[0 1 0]
[2 4 0]]
[[4 2 0]
[3 3 4]
[0 4 0]]
[[3 4 0]
[2 2 1]
[0 0 4]]
[[3 1 2]
[4 3 4]
[2 0 3]]
[[3 4 2]
[3 1 0]
[1 0 0]]
[[ 2.6 2.2 0.8]
[ 2.4 2. 1.8]
[ 1. 1.6 1.4]]
如果你仍然想循环,你可以使用嵌套循环,如:
for row in range(array.shape[0]):
for col in range(array.shape[1]):
cell_value = array[row, col]
...
给定一个二维数组。