0
r =  np.arange(36)
r.resize((6,6))

output:
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]
 [24 25 26 27 28 29]
 [30 31 32 33 34 35]]

My questions are:

  1. How can I extract a sub-array from the full matrix?

Example:

 [[14 15],                                                                            
  [20 21]]
  1. What the difference between resize and reshape syntax in numpy?
roganjosh
  • 12,594
  • 4
  • 29
  • 46

1 Answers1

1
  1. You can extract the desired portion of the array by sliceing operation:
r =  np.arange(36)
r = r.reshape((6, 6))    
r[2:4, 2:4]
  • numpy.resize receives the numpy.array to be resized and new_shape (which is of type int or tuple of ints), that represent the shape of the resized array, and returns the resized numpy.array.
  • numpy.reshape receives the numpy.array to be reshaped and a newshape (which is again of type int or tuple of ints), that represent the desired shape of the output array, and returns the reshaped numpy.array.

The main difference between the two methods, is that resize pads the output to match the desired shape, while reshape will throw an error if the requested shape does not fit the data.

For example:

r =  np.arange(36)
r = r.reshape((6, 1))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-165-36ecb32eda6e> in <module>
      1 r =  np.arange(36)
----> 2 r = r.reshape((6, 1))
      3 r[2:4, 2:4]

ValueError: cannot reshape array of size 36 into shape (6,1)

while if you'd use resize it will output the desired array:

r =  np.arange(36)
r.resize((6,1))
r


array([[0],
       [1],
       [2],
       [3],
       [4],
       [5]])
Michael
  • 2,167
  • 5
  • 23
  • 38