本文共 2131 字,大约阅读时间需要 7 分钟。
使用 numpy.reshape 修改数组形状,保留数据不变。
a = np.arange(8)b = a.reshape(4, 2, order='C')
a 初始形状为 (8,)b 变为 ((4, 2),),按列排列输出结果:
a = [0 1 2 3 4 5 6 7]b = [[0 1], [2 3], [4 5], [6 7]]
使用 flat 属性遍历数组元素,保持原始数据不变。
a = np.arange(4).reshape(2, 2)
a 形状为 (2, 2)输出结果:
原始数组 a: [[0 1] [2 3]]
使用 flatten 和 ravel 展平数组,按不同顺序处理。
a = np.arange(8).reshape(2, 4)
a 形状为 (2, 4)输出结果:
原始数组 a: [[0 1 2 3] [4 5 6 7]]展平按列顺序 `flatten(order='C')`: [0 1 2 3 4 5 6 7]展平按行顺序 `flatten(order='F')`: [0 4 1 5 2 6 3 7]转置数组 `transpose`: [[0 4], [1 5], [2 6], [3 7]]
使用 where 和索引操作快速定位数组元素。
a = np.arange(8).reshape(2, 4)
a 形状为 (2, 4)输出结果:
np.where(a > 6): (array([1, 1, 1], dtype=int64), array([1, 2, 3], dtype=int64))a[where(a > 4)]: [5, 6, 7]
使用 rollaxis 和 swapaxes 调整数组维度。
b = a.reshape(2, 2, 2)c = np.rollaxis(b, 2, 0)d = np.rollaxis(b, 2, 1)
b 形状为 (2, 2, 2)c 将轴 2 滚动到轴 0:((2, 2),)d 将轴 2 滚动到轴 1:((2, 2),)输出结果:
b = [[[0 1], [2 3]], [[4 5], [6 7]]]c = [[[0 2], [4 6]], [[1 3], [5 7]]]d = [[[0 2], [1 3]], [[4 6], [5 7]]]
使用 broadcast 和 concatenate 合并数组。
x = np.array([[1], [2], [3]])y = np.array([4, 5, 6])b = np.broadcast(x, y)c = np.empty(b.shape)c.flat = [u + v for (u, v) in b]
x 形状 (3,)y 形状 (3,)b 广播结果 (3, 3)c 填充后形状 (3, 3)输出结果:
c.flat = [5, 6, 7, 6, 7, 8, 7, 8, 9]
使用 stack、hstack、vstack、split 进行数组拼接与分割。
a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6], [7, 8]])堆叠(`stack`)结果:
沿轴 0 堆叠:
[[[1, 2], [3, 4]],[[5, 6], [7, 8]]]沿轴 1 堆叠:
[[[1, 2], [5, 6]],[[3, 4], [7, 8]]]## 数组操作扩展使用 `append`、`insert`、`delete` 进行数组操作。 ```pythona = np.array([[1, 2], [3, 4]])b = np.array([[5, 6], [7, 8]])延轴 0 插入:[[1, 2], [3, 4], [7, 8, 9]]延轴 1 插入:[[1, 2, 5, 6], [3, 4, 7, 8]]删除第二列:[[1, 3], [4, 6]]
使用 unique 去重并重构原始数组。
a = np.array([5, 2, 6, 2, 7, 5, 6, 8, 2, 9])u, indices, inverse, counts = np.unique(a, return_index=True, return_inverse=True, return_counts=True)
u:[2, 5, 6, 7, 8, 9]indices:[1, 0, 2, 4, 7, 9]inverse:[1, 0, 2, 0, 3, 1, 2, 4, 0, 5]counts:[3, 2, 2, 1, 1, 1]输出结果:
u[inverse] = [5, 2, 6, 2, 7, 5, 6, 8, 2, 9]
转载地址:http://rwlfk.baihongyu.com/