.Changing the number of Dimensions
broadcast_to
Broadcast an array to a new shape.
It returns a read-only view on the original array. It is typically not contiguous.
The function may throw ValueError if the new shape does not comply with NumPy’s broadcasting rules.
This function is available version 1.10.0 onwards.
broadcast_to(array, shape, subok=False) array: The array to broadcast. shape: The shape of the desired array. subok: If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).
>>> a=np.array([1,2,3,4]) >>> b=np.broadcast_to(a,(4,4),subok=False) >>> b [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
broadcast
NumPy has in-built support for broadcasting. This function mimics the broadcasting mechanism.
It returns an object that encapsulates the result of broadcasting one array against the other.
broadcast(...) in1, in2, ... :Input parameters.
>>> y=np.array([[10,10,10,10],[20,20,20,20],[30,30,30,30],[40,40,40,40]]) >>> z=np.array([1,2,3,4]) >>> b=np.broadcast(y,z) >>> y+z array([[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]])
expand_dims
Expand the shape of an array.
Insert a new axis that will appear at the axis position in the expanded array shape.
expand_dims(a, axis) a: Input array. axis: Position in the expanded axes where the new axis is placed.
>>> x = np.array([1,2]) [1, 2] >>> x.ndim 1 >>> x.shape (2,) >>> y = np.expand_dims(x, axis=0) [[1, 2]] >>> y.ndim 2 >>> y.shape (1, 2) >>> y1=np.expand_dims(x,axis=1) >>> y1 [[1], [2]] >>> y1.ndim 2 >>> y1.shape (2, 1)
squeeze
This function removes a one-dimensional entry from the shape of the given array. Two parameters are required for this function.
squeeze(a, axis=None) a-Input data. axis-None or int or tuple of ints, optional. value error occurred when If the axis is not None, and an axis being squeezed is not of length 1
>>> a=np.array([[[1],[2],[3]]]) >>> a.shape (1, 3, 1) >>> b=np.squeeze(a) >>> b.shape (3,) >>> np.squeeze(a,axis=(0,2)).shape (3,) >>> np.squeeze(a,axis=2).shape (1, 3) >>> x = np.arange(4).reshape(1,2,2) (1, 2, 2) >>> np.squeeze(x).shape (2, 2) >>> np.squeeze(x,axis=0).shape (2, 2) >>> np.squeeze(x,axis=1).shape ValueError: cannot select an axis to squeeze out which has size not equal to one