51

I have a two-dimensional array with shape (x, y) which I want to convert to a three-dimensional array with shape (x, y, 1). Is there a nice Pythonic way to do this?

10 Answers 10

77

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)
Sign up to request clarification or add additional context in comments.

8 Comments

On a side note, numpy.newaxis is just None. newaxis is "just" for readibility. It's equivalent to just do b = a[..., None] (The ellipsis also allows it to work for N-dimensional arrays, not just 2D arrays.)
True. For some reason I had the impression that newaxis being None was just an implementation detail (and therefore possibly subject to change in the future), but it looks like it's explicitly documented.
Suppose you want the third axis to be something other than 1? e.g. how do you convert a to be b with b.shape = (6,8,3)?
@Gathide: That depends. Your old array has 6*8 = 48 numbers in it. The new one has 6*8*3 = 144 numbers. How do you want to map the original 48 numbers into your new array? Repeat along the third axis? In which case, most of the time you don't bother with the repetition: leave it as shape (6, 8, 1) and make use of NumPy's ability to broadcast. But if you really need shape (6, 8, 3), look into np.tile and np.broadcast_to.
@Gathide as Mark Dickinson says you can do this with np.broadcast_to like b = np.broadcast_to(a[..., np.newaxis], (6, 8, 3)).
|
20
numpy.reshape(array, array.shape + (1,))

6 Comments

Thanks, I used A = A.reshape(A.shape + (1,))
If you're happy to modify A in place, you can simply assign to the shape attribute: A.shape = A.shape + (1,), or even A.shape += 1,.
assuming that i have a 3D [1000,10,5] array and I want to convert it to a 2D with shape [1000, 50] like concatenating the 2nd and 3rd initial dimensions. Is reshape fine in this case?
yea it's sure
@serafeim, sure.
Thanks. I noticed that the desired outcome is when I use order='F' inside np.reshape. If order='F' is NOT specified, then the output is wrong in my case
12
import numpy as np

# Create a two-dimensional 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)

Comments

4
import numpy as np

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

Comments

3

I hope this function helps you to convert the two-dimensional array to a three-dimensional 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)

Comments

2

If you just want to add a third 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.

Comments

1
import numpy as np
# create a 2-D ndarray
a = np.array([[2,3,4], [5,6,7]])
print(a.ndim)
>> 2
print(a.shape)
>> (2, 3)

# add 3rd dimension

1st option: reshape

b = np.reshape(a, a.shape + (1,))
print(b.ndim)
>> 3
print(b.shape)
>> (2, 3, 1)

2nd option: expand_dims

c = np.expand_dims(a, axis=2)
print(c.ndim)
>> 3
print(c.shape)
>> (2, 3, 1)

Comments

1

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.

Comments

1

A simple way, with some math

At first, you know the number of array elements, let’s say 100 and then divide 100 in three steps like:

25 * 2 * 2 = 100

or: 4 * 5 * 5 = 100

import numpy as np
D = np.arange(100)
# Change to three-dimensional 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 four-dimensional:

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

Comments

0

If you have an array

a2 = np.array([[1, 2, 3.3],
           [4, 5, 6.5]])

then you can change this array into a three-dimensional array of shape (2, 3, 3) by using:

a2_new = np.reshape(a2, a2.shape + (1,)) a2_new

Your output will be:

array([[[1. ],
    [2. ],
    [3.3]],

   [[4. ],
    [5. ],
    [6.5]]])

Or

You can try:

a2.reshape(2, 3, 1)

This will change your two-dimensional array to three-dimensional of shape(2, 3, 1).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.