Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

Assist me in creating a 4d array. Below is my code for 3 dimension array. How do I get output in the shape of (4,3,2,3)

Three_d_array - numpy.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]],[[13,14,15],[16,17,18]]])

2 Answers

0 votes
by (36.8k points)

import numpy as np    

a = np.arange(72)

a = np.reshape(a, (4,3,2,3))

OR

a = np.array([[[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]],[[13,14,15],[16,17,18]]], [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]],[[13,14,15],[16,17,18]]], [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]],[[13,14,15],[16,17,18]]], [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]],[[13,14,15],[16,17,18]]]])

OR

a = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]],[[13,14,15],[16,17,18]]])

a = np.expand_dims(a, axis=0)

a = np.repeat(a, 4, axis=0)

If you are a beginner and want to know more about Data Science the do check out the Data Science course

For more information, kindly refer to our Python Certification course.

0 votes
ago by (1.9k points)

The used array has dimensions of (3, 2, 3). In simpler words it is comprised of 3 blocks, with each block containing 2 rows of 3 elements each.

In the transformation process of the 3D array to a 4D array of (4, 3, 2, 3) it is required to add an extra dimension with the appropriate size using np.tile.

import numpy as ny

3D_array = ny.array([

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

[[7, 8, 9], [10, 11, 12]],

[[13, 14, 15], [16, 17, 18]]

])

4_d_array = ny.tile(3D_array, (4, 1, 1, 1))

print(4_d_array)

print(“Shape of the new array:” , 4_d_array.shape)

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...