lionel319
lionel319

Reputation: 1256

how to add dimensions to a numpy element?

i have a numpy.array like this

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

How can i change it to this:-

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

Thanks in advance.

Upvotes: 0

Views: 65

Answers (4)

Paul Panzer
Paul Panzer

Reputation: 53029

Disclaimer: This one is fast (for large operands), but pretty unsound. Also it only works for 32 or 64 bit dtypes. Do not use in serious code.

def squeeze_in_zero(a):
    sh = a.shape
    n = a.dtype.itemsize
    return a.view(f'f{n}').astype(f'c{2*n}').view(a.dtype).reshape(*a.shape, 2)

Speedwise at 10000 elements on my machine it is roughly on par with @Divakar's array assignment. Below it is slower, above it is faster.

Sample run:

>>> a = np.arange(-4, 5).reshape(3, 3)
>>> squeeze_in_zero(a)
array([[[-4,  0],
        [-3,  0],
        [-2,  0]],

       [[-1,  0],
        [ 0,  0],
        [ 1,  0]],

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

Upvotes: 1

ZisIsNotZis
ZisIsNotZis

Reputation: 1740

If your input is unsigned integer and your dtype is "large enough", you can use the following code to pad zero without creating copy:

b = str(a.dtype).split('int')
b = a[...,None].view(b[0]+'int'+str(int(b[1])//2))

with a equal to your example, the output looks like

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

       [[4, 0],
        [5, 0],
        [6, 0]],

       [[7, 0],
        [8, 0],
        [9, 0]]], dtype=int16)

Upvotes: 2

Divakar
Divakar

Reputation: 221504

With a as the input array, you can use array-assignment and this would work for a generic n-dim input -

out = np.zeros(a.shape+(2,),dtype=a.dtype)
out[...,0] = a

Sample run -

In [81]: a
Out[81]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [82]: out = np.zeros(a.shape+(2,),dtype=a.dtype)
    ...: out[...,0] = a

In [83]: out
Out[83]: 
array([[[1, 0],
        [2, 0],
        [3, 0]],

       [[4, 0],
        [5, 0],
        [6, 0]],

       [[7, 0],
        [8, 0],
        [9, 0]]])

If you play around with broadcasting, here's a compact one -

a[...,None]*[1,0]

Upvotes: 5

Statistic Dean
Statistic Dean

Reputation: 5270

I think numpy.dstack might provide the solution. Let's call A your first array. Do

B = np.zeros((3,3))
R = np.dstack((A,B))

And R should be the array you want.

Upvotes: 2

Related Questions