Transposing, Flattening and Reshaping arrays using NumPy

Nikitajain Jain
4 min readJan 18, 2024

--

Example #1: Using numpy.transpose()

It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays.

import numpy as np
# Making a 3x3 array
gfg = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Before transpose
print("Original Array:")
print(gfg, end='\n\n')
# After transpose using numpy.transpose()
print("Transposed Array:")
print(np.transpose(gfg))

Example #2: Using ndarray.T with Tuple

Parameters:
axes : [None, tuple of ints, or n ints] If anyone wants to pass the parameter then you can but it’s not all required. But if you want than remember only pass (0, 1) or (1, 0). Like we have array of shape (2, 3) to change it (3, 2) you should pass (1, 0) where 1 as 3 and 0 as 2.
Returns: ndarray

import numpy as np
# Making a 3x2 array
gfg = np.array([[1, 2],
[4, 5],
[7, 8]])
# Before transpose
print("Original Array:")
print(gfg, end='\n\n')
# After transpose using ndarray.T with tuple (1, 0)
print("Transposed Array:")
print(gfg.T)
Output
Original Array:
[[1 2]
[4 5]
[7 8]]
Transposed Array:
[[1 4 7]
[2 5 8]]
# NOTE : 
gfg.T ==gfg.transpose()

for a 2D array :

gfg.transpose()=gfg.transpose(1,0)

USE CASES

  1. In adjusting model parameters in backpropagation in CNN.

2. In principal component analysis (PCA) or singular value decomposition (SVD), transposition is involved in computing eigenvectors and singular vectors.

3. In computer vision applications, transposition can be used for image processing tasks such as rotating or flipping images.

FLATTENING ARRAYS

Syntax:numpy_array.flatten(order=’C’)
  • order:‘C’ means to flatten in row-major.’F’ means to flatten in column-major.’ Defalut is order=’C’.
credit — geeksforgeeks
import numpy as np 

# declare matrix with np
gfg = np.array([[2, 3], [4, 5]])

# using array.flatten() method
flat_gfg = gfg.flatten()
print(flat_gfg)

Output: [2 3 4 5]

Use Cases:

  • Neural Networks: Flatten layers are commonly used in neural networks to transform the output of convolutional layers into a format suitable for fully connected layers.
  • Feature Vectors: Some machine learning algorithms, such as support vector machines, expect input features in a one-dimensional format. Flattening is used to convert multi-dimensional feature representations into a flat feature vector.

RESHAPING AN ARRAY

Syntax

ndarray.reshape(new_shape)

CASES:

(1) We already know the desired number dimensions (say rows and columns) of the reshaped array.

(2) We know the desired number of columns, but don’t know the desired number of rows of the reshaped array or vice-versa.

Lets us take the first case — Reshaping a numpy array when the number of rows and number of columns of the reshaped array is known.

  • This technique is used when you already are aware — how many numbers of rows and columns your reshaped array will have.
my_arr = np.arange(6) 
 print(my_arr)
  • output :[0,1,2,3,4,5]
  • Reshaping now
my_new_arr = my_arr.reshape(2,3)  
print(my_new_arr)
  • output :
  • [ [0,1,2], [3,4,5] ]

Now, let us take the second case — Reshaping a numpy array when the desired number of columns is known, but the desired number of rows is unknown.

  • To achieve this, you use a value of ‘-1’ in place of ‘rows’ field in the reshape() function, and use the desired value of the number of columns you want in the columns field in the reshape() function.
  • Example — Say you want to reshape an existing array to an array with 3 columns and an unknown number of rows, as shown in the code below:
my_arr = np.arange(9)  
print(my_arr)
  • output will be
  • [0,1,2,3,4,5,6,7,8]
  • Now, let us reshape this array
my_new_arr = my_arr.reshape(-1,3)  
print(my_new_arr)
  • output will be
  • [ [0,1,2], [3,4,5], [6,7,8] ]

When you can’t use reshape() function?

You can't use reshape() function, when the size of the original array is different from your desired reshaped array. If you try to reshape(), it will throw an error.

  • Example
my_arr = np.arange(8) 
print(my_arr)
  • output will be
  • [0,1,2,3,4,5,6,7]
my_arr.reshape(2,3)
  • the output will be an error as shown below
  • ValueError: cannot reshape array of size 8 into shape (2,3)

USE CASES

Image Data for Convolutional Neural Networks (CNNs):

  • Images are typically represented as 3D arrays (height x width x channels). CNNs expect input in the form of 4D arrays (batch_size x height x width x channels). Reshaping is used to convert image data into the required format before feeding it into the network.

So we conclude our basics operations of NumPy array .Array broadcasting will be dealt in next blog.

--

--

Nikitajain Jain

To be data scientist ,love creating value out of numbers . Pursing MSc DS from Banasthli Vidhyapith. Interested in AI, ML, NLP, spirituality , society