Petr Peller
Petr Peller

Reputation: 8846

Insert item and change the array's dimension

I want to add dimensions to an array, but expand_dims always adds dimension of size 1.

Input:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

What expand_dims does:

[[[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]]

What I want:

[[[1, 1], [1, 2], [1, 3]], [[1, 4], [1, 5], [1, 6]], [[1, 7], [1, 8], [1, 9]]]

Basically I want to replace each scalar in the matrix by a vector [1, x] where x is the original scalar.

Upvotes: 3

Views: 140

Answers (2)

hpaulj
hpaulj

Reputation: 231665

There are lots of ways of constructing the new array.

You could initial the array with right shape and fill, and copy values:

In [402]: arr = np.arange(1,10).reshape(3,3)
In [403]: arr
Out[403]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
In [404]: res = np.ones((3,3,2),int)
In [405]: res[:,:,1] = arr
In [406]: res
Out[406]: 
array([[[1, 1],
        [1, 2],
        [1, 3]],

       [[1, 4],
        [1, 5],
        [1, 6]],

       [[1, 7],
        [1, 8],
        [1, 9]]])

You could join the array with a like size array of 1s. concatenate is the basic joining function:

In [407]: np.concatenate((np.ones((3,3,1),int), arr[:,:,None]), axis=2)
Out[407]: 
array([[[1, 1],
        [1, 2],
        [1, 3]],

       [[1, 4],
        [1, 5],
        [1, 6]],

       [[1, 7],
        [1, 8],
        [1, 9]]])

np.stack((np.ones((3,3),int), arr), axis=2) does the same thing under the covers. np.dstack ('d' for depth) does it as well. The insert in the other answer also does this.

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107347

Here's one way using broadcasting and np.insert() function:

In [32]: a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 
In [33]: np.insert(a[:,:,None], 0, 1, 2)                                                                                                                                                                    
Out[33]: 
array([[[1, 1],
        [1, 2],
        [1, 3]],

       [[1, 4],
        [1, 5],
        [1, 6]],

       [[1, 7],
        [1, 8],
        [1, 9]]])

Upvotes: 1

Related Questions