How to reshape a Numpy array in Python?

How to reshape a Numpy array in Python?

This recipe helps you reshape a Numpy array in Python

Machine learning data is largely stored as arrays. Python almost always uses NumPy arrays to store such data. In the data manipulation step of your project, it is important to be able to perform basic data manipulation using NumPy arrays.

This is because some algorithms such as the Long Short-Term Memory (LSTM) recurrent neural network in Keras or certain Python libraries, require input to be in the format of a 3-dimensional array. Many times you will need to reshape 2-dimensional data where each row represents a sequence into a 3-dimensional array for algorithms that expect multiple samples.

The numpy.reshape() tool shapes an array without changing the data of the array. It gives a new shape to an array without changing the underlying data. The python numpy reshape() method doesn’t modify the contents of the original NumPy array. It only produces a new array. This means that you will have to save the output of the method in some form, most likely into a new NumPy array.

References :

https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.reshape.html

https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

In [2]:
## How to Reshape a Numpy Array or Matrix
def Kickstarter_Example_4():
    print()
    print(format('How to Reshape a Numpy Array', '*^52'))

    # Load library
    import numpy as np

    # Create a 4x3 matrix
    matrix = np.array([[1, 2, 3],
                       [4, 5, 6],
                       [7, 8, 9],
                       [10, 11, 12]])

    # Reshape matrix into 2x6 matrix
    print()
    print(matrix.reshape(2, 6))

    print()
    print(matrix.reshape(3, 4))

    print()
    print(matrix.reshape(6, 2))

Kickstarter_Example_4()
************How to Reshape a Numpy Array************

[[ 1  2  3  4  5  6]
 [ 7  8  9 10 11 12]]

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]]


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
1 developer from IQVIA
1 developer from MudraCircle
1 developer from Sony
1 developer from YASH Technologies
1 developer from Altimetrik
1 developer from KPMG
1 developer from New Delhi DataPoint
1 developer from Tech Mahindra
1 developer from ANAC
1 developer from LTI