Python NumPy (Page: 2)

NumPy shape and reshaping

Sometimes it is very easy to initialize one-dimensional array and then cut it into multi-dimensional array. This procedure called “reshaping”

Identifying shape of existing NymPy array

We can check shape or dimension and size of any NumPy array with property ‘shape’


start = [[1,2,3],[4,5,6]] # list of lists
a_2D = np.array(start)    # 2D array [[1 2 3] [4 5 6]]
print(a_2D.shape  )       # shape of array (2,3) (rows, columns)

Simple reshaping

If we have linear (one dimensional) array, we can reshape it into array with any amount of dimensions, but it necessary to keep eye on proper size. If it will be mismatch in amount of data for reshaping, the error will be produces.


a_1D = np.arange(8)      # [0 1 2 3 4 5 6 7]
a_2D = a_1D.reshape(2,4) # [[0 1 2 3] [4 5 6 7]] - reshape to  2r x 4c
b_2D = a_1D.reshape(2,5) # ValueError

Creating similar array

Another opportunity is to create similar array, filled with some basic values. We have very similar functions:

  • empty_like - Return an empty array with shape and type of input
  • ones_like - Return an array of ones with shape and type of input
  • full_like - Return a new array with shape of input filled with value given as argument
  • zeros_like - Return a new array setting values to zero

All these functions are very similar in use:


a_1D = np.arange(8)           # [0 1 2 3 4 5 6 7]
a_2D = a_1D.reshape(2,4)      # [[0 1 2 3] [4 5 6 7]] - reshape to  2r x 4c
b0_2D = np.zeros_like(a_2D)   # [[0 0 0 0] [0 0 0 0]] - the same type
b1_2D = np.ones_like(a_2D)    # [[1 1 1 1] [1 1 1 1]] - the same type
be_2D = np.empty_like(a_2D)   # [[1 1 1 1] [1 1 1 1]] - the same type (value can be any)
bf_2D = np.full_like(a_2D, 2) # [[2 2 2 2] [2 2 2 2]] - the same type (value need to defiend)

Output

set_printoptions - can be used to change output of array with command print

Go to Page: 1; 2; 3; 4; 5; 6;


Published: 2021-10-04 11:48:19
Updated: 2021-11-14 08:41:55