39
votes

I have a 2d array with shape (x, y) which I want to convert to a 3d array with shape (x, y, 1). Is there a nice Pythonic way to do this?

8

8 Answers

64
votes

In addition to the other answers, you can also use slicing with numpy.newaxis:

>>> from numpy import zeros, newaxis
>>> a = zeros((6, 8))
>>> a.shape
(6, 8)
>>> b = a[:, :, newaxis]
>>> b.shape
(6, 8, 1)

Or even this (which will work with an arbitrary number of dimensions):

>>> b = a[..., newaxis]
>>> b.shape
(6, 8, 1)
14
votes
numpy.reshape(array, array.shape + (1,))
6
votes
import numpy as np

# create a 2D array
a = np.array([[1,2,3], [4,5,6], [1,2,3], [4,5,6],[1,2,3], [4,5,6],[1,2,3], [4,5,6]])

print(a.shape) 
# shape of a = (8,3)

b = np.reshape(a, (8, 3, -1)) 
# changing the shape, -1 means any number which is suitable

print(b.shape) 
# size of b = (8,3,1)
3
votes
import numpy as np

a= np.eye(3)
print a.shape
b = a.reshape(3,3,1)
print b.shape
2
votes

hope this funtion helps u to convert 2D array to 3D array.

Args:
  x: 2darray, (n_time, n_in)
  agg_num: int, number of frames to concatenate. 
  hop: int, number of hop frames. 

Returns:
  3darray, (n_blocks, agg_num, n_in)


def d_2d_to_3d(x, agg_num, hop):

    # Pad to at least one block. 
    len_x, n_in = x.shape
    if (len_x < agg_num): #not in get_matrix_data
        x = np.concatenate((x, np.zeros((agg_num - len_x, n_in))))

    # main 2d to 3d. 
    len_x = len(x)
    i1 = 0
    x3d = []
    while (i1 + agg_num <= len_x):
        x3d.append(x[i1 : i1 + agg_num])
        i1 += hop

    return np.array(x3d)
1
votes

If you just want to add a 3rd axis (x,y) to (x,y,1), Numpy allows you to easily do this using the dstack command.

import numpy as np
a = np.eye(3) # your matrix here
b = np.dstack(a).T

You need to transpose (.T) it to get it into the (x,y,1) format you want.

0
votes

You can do this with reshape

For example, you have an array A of shape 35 x 750 (two dimensions), you can change the shape to 35 x 25 x 30 (three dimensions) with A.reshape(35, 25, 30)

More in the documentation here

0
votes

simple way , with some math

at first you know the number of array elements , lets say 100 and then devide 100 on 3 steps like:

25 * 2 * 2 = 100

or: 4 * 5 * 5 = 100

import numpy as np
D = np.arange(100)
# change to 3d by division of 100 for 3 steps 100 = 25 * 2 * 2
D3 = D.reshape(2,2,25) # 25*2*2 = 100

another way:

another_3D = D.reshape(4,5,5)
print(another_3D.ndim)

to 4D:

D4 = D.reshape(2,2,5,5)
print(D4.ndim)