Home > database >  Create a new dimension with a Desired Size than 1 in Numpy
Create a new dimension with a Desired Size than 1 in Numpy

Time:11-15

I was Wondering while working with Numpy Array that if I have a 2d-Array of size (20,20) and I want to add a new Dimension of a certain size, How can I do it in Python.

Whenever I use np.expand_dims or np.newAxis it always will expand my existing array like this (20,20,1), I want it to be (20,20,10).

Please Guide me on this as I am new to NumPy and I couldn't find a solution to it anywhere with my keyword search on Google.

I am Transitioning from Java to Python. Informing about this so you guys can know what I am struggling with java in mind.

import numpy as np
a = np.arange(6).reshape((2, 3))
print('2d Array')
print(a.shape)

# create 3d Array with size (2,3,5) and not (2 , 3 ,1)

Example input:

array([[0, 1, 2],
       [3, 4, 5]])

CodePudding user response:

You can use numpy.repeat:

b = np.repeat(a[:, :, None], 5, axis=2)

Output:

>>> b.shape
(2, 3, 5)

>>> b
array([[[0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2]],

       [[3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4],
        [5, 5, 5, 5, 5]]])

Or numpy.tile:

b = np.tile(a[:, :, None], 5)

Output:

array([[[0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2]],

       [[3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4],
        [5, 5, 5, 5, 5]]])

CodePudding user response:

What is your desired output?

Maybe you mean that:

b = np.vstack(([[a] for i in range(5)]))

Output:

array([[[0, 1, 2],
        [3, 4, 5]],

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

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

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

       [[0, 1, 2],
        [3, 4, 5]]])

shape is : (5,2,3) if that's not your meant and you want (2,3,5) and repeat any element 5 times you can use:

  b= np.tile(a[: ,: ,np.newaxis],5)
  • Related