Hướng dẫn dùng np.resize python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    With the help of Numpy numpy.resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing.

    Parameters:
    new_shape : [tuple of ints, or n ints] Shape of resized array
    refcheck : [bool, optional] This parameter is used to check the reference counter. By Default it is True.

    Returns: None

    Most of you are now thinking that what is the difference between reshape and resize. When we talk about reshape then an array changes it’s shape as temporary but when we talk about resize then the changes made permanently.

    Example #1:
    In this example we can see that with the help of .resize() method, we have changed the shape of an array from 1×6 to 2×3.

    import numpy as np

    gfg = np.array([1, 2, 3, 4, 5, 6])

    gfg.resize(2, 3)

    print(gfg)

    Output:

    [[1 2 3]
     [4 5 6]]
    

    Example #2:
    In this example we can see that, we are trying to resize the array of that shape which is type of out of bound values. But numpy handles this situation to append the zeros when values are not existed in the array.

    import numpy as np

    gfg = np.array([1, 2, 3, 4, 5, 6])

    gfg.resize(3, 4)

    print(gfg)

    Output:

    [[1 2 3 4]
     [5 6 0 0]
     [0 0 0 0]]
    

    In Python, if the input is a numpy array, you can use np.lib.pad to pad zeros around it -

    import numpy as np
    
    A = np.array([[1, 2 ],[2, 3]])   # Input
    A_new = np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0)) # Output
    

    Sample run -

    In [7]: A  # Input: A numpy array
    Out[7]: 
    array([[1, 2],
           [2, 3]])
    
    In [8]: np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0))
    Out[8]: 
    array([[1, 2, 0, 0],
           [2, 3, 0, 0],
           [0, 0, 0, 0]])  # Zero padded numpy array
    

    If you don't want to do the math of how many zeros to pad, you can let the code do it for you given the output array size -

    In [29]: A
    Out[29]: 
    array([[1, 2],
           [2, 3]])
    
    In [30]: new_shape = (3,4)
    
    In [31]: shape_diff = np.array(new_shape) - np.array(A.shape)
    
    In [32]: np.lib.pad(A, ((0,shape_diff[0]),(0,shape_diff[1])), 
                                  'constant', constant_values=(0))
    Out[32]: 
    array([[1, 2, 0, 0],
           [2, 3, 0, 0],
           [0, 0, 0, 0]])
    

    Or, you can start off with a zero initialized output array and then put back those input elements from A -

    In [38]: A
    Out[38]: 
    array([[1, 2],
           [2, 3]])
    
    In [39]: A_new = np.zeros(new_shape,dtype = A.dtype)
    
    In [40]: A_new[0:A.shape[0],0:A.shape[1]] = A
    
    In [41]: A_new
    Out[41]: 
    array([[1, 2, 0, 0],
           [2, 3, 0, 0],
           [0, 0, 0, 0]])
    

    In MATLAB, you can use padarray -

    A_new  = padarray(A,[1 2],'post')
    

    Sample run -

    >> A
    A =
         1     2
         2     3
    >> A_new = padarray(A,[1 2],'post')
    A_new =
         1     2     0     0
         2     3     0     0
         0     0     0     0
    
    numpy.resize(a, new_shape)[source]#

    Return a new array with the specified shape.

    If the new array is larger than the original array, then the new array is filled with repeated copies of a. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a.

    Parametersaarray_like

    Array to be resized.

    new_shapeint or tuple of int

    Shape of resized array.

    Returnsreshaped_arrayndarray

    The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated iterating over the array in C-order.

    Notes

    When the total size of the array does not change reshape should be used. In most other cases either indexing (to reduce the size) or padding (to increase the size) may be a more appropriate solution.

    Warning: This functionality does not consider axes separately, i.e. it does not apply interpolation/extrapolation. It fills the return array with the required number of elements, iterating over a in C-order, disregarding axes (and cycling back from the start if the new shape is larger). This functionality is therefore not suitable to resize images, or data where each axis represents a separate and distinct entity.

    Examples

    >>> a=np.array([[0,1],[2,3]])
    >>> np.resize(a,(2,3))
    array([[0, 1, 2],
           [3, 0, 1]])
    >>> np.resize(a,(1,4))
    array([[0, 1, 2, 3]])
    >>> np.resize(a,(2,4))
    array([[0, 1, 2, 3],
           [0, 1, 2, 3]])
    

    Can we change size of array in Python?

    resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing.

    Can you modify the size of an array?

    The simple answer is that you cannot do this. Once an array has been created, its size cannot be changed. Instead, an array can only be "resized" by creating a new array with the appropriate size and copying the elements from the existing array to the new one.

    Can we change the size of NumPy array?

    there is no converting the dimensions of a numpy array in python. A numpy array is simply a section of your RAM. You can't append to it in the sense of literally adding bytes to the end of the array, but you can create another array and copy over all the data (which is what np. append(), or np.

    Can we modify array in Python?

    We can make changes to an array in different ways. Some of these are as follows: Assignment operator to change or update an array. Append() method to add one element.