Home  >  Article  >  Backend Development  >  How to Reshape a 4D NumPy Array to a 2D Array?

How to Reshape a 4D NumPy Array to a 2D Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 18:09:46897browse

How to Reshape a 4D NumPy Array to a 2D Array?

Intuition and Idea Behind Reshaping 4D Array to 2D Array in NumPy

In NumPy, reshaping multidimensional arrays requires an understanding of axis permutations and the reshape function. To reshape a 4D array to a 2D array, we typically follow a three-step process:

  1. Permute Axes: Rearrange the dimensions of the array to match the desired output shape. This is done using functions like transpose, moveaxis, rollaxis, or swapaxes.
  2. Split or Merge Axes: Adjust the dimensionality of the array by creating new axes (splitting) or combining existing axes (merging).
  3. Reshape: Use the reshape function to adjust the shape of the array to the desired output size.

Example

Consider the following 4D array:

array([[[[ 0,  0],
         [ 0,  0]],

        [[ 5, 10],
         [15, 20]]],


       [[[ 6, 12],
         [18, 24]],

        [[ 7, 14],
         [21, 28]]]])

To reshape it to (4,4):

  1. Permute Axes: We want the axes order to be (0, 1, 3, 2). This can be achieved using transpose:
a = a.transpose((2, 0, 3, 1))
  1. Split Axes: Perform no splitting, as we already have the correct number of dimensions.
  2. Reshape: Reshape to the desired shape:
a = a.reshape(4,4)

Result:

array([[ 0,  5,  0, 10],
       [ 6,  7, 12, 14],
       [ 0, 15,  0, 20],
       [18, 21, 24, 28]])

The above is the detailed content of How to Reshape a 4D NumPy Array to a 2D Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn