修改数组维度
numpy.broadcast
numpy.broadcast 用于模仿广播的对象,它返回一个对象,该对象封装了将一个数组广播到另一个数组的结果。
该函数使用两个数组作为输入参数
import numpy as npx = np.array([[1], [2], [3]])y = np.array([4, 5, 6]) # 对 y 广播 xb = np.broadcast(x,y) # 它拥有 iterator 属性,基于自身组件的迭代器元组print ('对 y 广播 x:')r,c = b.iters# Python3.x 为 next(context) ,Python2.x 为 context.next()print (next(r), next(c))print (next(r), next(c))print ('')# shape 属性返回广播对象的形状print ('广播对象的形状:')print (b.shape)print ('')# 手动使用 broadcast 将 x 与 y 相加b = np.broadcast(x,y)c = np.empty(b.shape)print ('手动使用 broadcast 将 x 与 y 相加:')print (c.shape)print ('')c.flat = [u + v for (u,v) in b]print ('调用 flat 函数:')print (c)print ('')# 获得了和 NumPy 内建的广播支持相同的结果print ('x 与 y 的和:')print (x + y)
输出结果为:
对 y 广播 x:1 41 5广播对象的形状:(3, 3)手动使用 broadcast 将 x 与 y 相加:(3, 3)调用 flat 函数:[[5. 6. 7.] [6. 7. 8.] [7. 8. 9.]]x 与 y 的和:[[5 6 7] [6 7 8] [7 8 9]]
numpy.broadcast_to
numpy.broadcast_to 函数将数组广播到新形状。它在原始数组上返回只读视图。 它通常不连续。 如果新形状不符合 NumPy 的广播规则,该函数可能会抛出ValueError。
numpy.broadcast_to(array, shape, subok)
import numpy as npa = np.arange(4).reshape(1,4)print ('原数组:')print (a)print ('')print ('调用 broadcast_to 函数之后:')print (np.broadcast_to(a,(4,4)))
输出结果为:
原数组:[[0 1 2 3]]调用 broadcast_to 函数之后:[[0 1 2 3] [0 1 2 3] [0 1 2 3] [0 1 2 3]]
numpy.expand_dims
numpy.expand_dims 函数通过在指定位置插入新的轴来扩展数组形状,函数格式如下:
numpy.expand_dims(arr, axis)
参数说明:
- arr:输入数组
- axis:新轴插入的位置
import numpy as np x = np.array(([1,2],[3,4])) print ('数组 x:')print (x)print ('')y = np.expand_dims(x, axis = 0) print ('数组 y:')print (y)print ('') print ('数组 x 和 y 的形状:')print (x.shape, y.shape)print ('')# 在位置 1 插入轴y = np.expand_dims(x, axis = 1)print ('在位置 1 插入轴之后的数组 y:')print (y)print ('')print ('x.ndim 和 y.ndim:')print (x.ndim,y.ndim)print ('')print ('x.shape 和 y.shape:')print (x.shape, y.shape)
输出结果为:
数组 x:[[1 2] [3 4]]数组 y:[[[1 2] [3 4]]]数组 x 和 y 的形状:(2, 2) (1, 2, 2)在位置 1 插入轴之后的数组 y:[[[1 2]] [[3 4]]]x.ndim 和 y.ndim:2 3x.shape 和 y.shape:(2, 2) (2, 1,