Concatenate two NumPy arrays in the 4th dimension in Python

Learn, how to concatenate two NumPy arrays in the 4th dimension in Python? By Pranit Sharma Last updated : April 06, 2023

Suppose that we are given two numpy arrays with three dimensions (3 x 4 x 5) and we want to concatenate them so the result has four dimensions (3 x 4 x 5 x 2).

Concatenating two NumPy arrays in the 4th dimension

To concatenate two NumPy arrays in the 4th dimension, if we directly use, numpy.concatenate((arr1,arr2)), it will generate an error. Hence, we need to add a new axis and then we can concatenate them to the 4th dimension. We can do this by using the following command:

np.concatenate((arr1[...,np.newaxis],arr2[...,np.newaxis]),axis=3

Which will give us a (3 x 4 x 5 x 2) array. We can also use None in place of newaxis as both are equivalent.

Let us understand with the help of an example,

Python code to concatenate two NumPy arrays in the 4th dimension

# Import numpy
import numpy as np

# Creating two array
arr1 = np.ones((3,4,5))
arr2 = np.ones((3,4,5))

# Display original arrays
print("array 1:\n",arr1,"\n")
print("array 2:\n",arr2,"\n")

# Concatenating array to 4th dimension
res = np.concatenate((arr1[...,np.newaxis],arr2[...,np.newaxis]),axis=3)

# Display result
print("Result:\n",res,"\n")

Output

array 1:
 [[[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]

 [[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]

 [[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]] 

array 2:
 [[[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]

 [[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]

 [[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]] 

Result:
 [[[[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]

  [[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]

  [[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]

  [[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]]


 [[[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]

  [[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]

  [[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]

  [[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]]


 [[[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]

  [[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]

  [[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]

  [[1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]
   [1. 1.]]]] 

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.