1

I have a problem with a numpy array.

In particular, suppose to have a matrix

x = np.array([[1., 2., 3.], [4., 5., 6.]])

with shape (2,3), I want to convert the float numbers into list so to obtain the array [[[1.], [2.], [3.]], [[4.], [5.], [6.]]] with shape (2,3,1). I tried to convert each float number to a list (i.e., x[0][0] = [x[0][0]]) but it does not work.

Can anyone help me? Thanks

Ehsan
  • 12,072
  • 2
  • 20
  • 33
mht
  • 381
  • 1
  • 2
  • 12

5 Answers5

2

What you want is adding another dimension to your numpy array. One way of doing it is using reshape:

x = x.reshape(2,3,1)

output:

[[[1.]
  [2.]
  [3.]]

 [[4.]
  [5.]
  [6.]]]
Ehsan
  • 12,072
  • 2
  • 20
  • 33
1

Actually, you want to add a dimension (not level).

To do it, run:

result = x[...,np.newaxis]

Its shape is just (2, 3, 1).

Or save the result back under x.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
1

There is a function in Numpy to perform exactly what @Valdi_Bo mentions. You can use np.expand_dims and add a new dimension along axis 2, as follows:

x = np.expand_dims(x, axis=2)

Refer: np.expand_dims

Nikhil Kumar
  • 1,015
  • 1
  • 9
  • 14
0

You are trying to add a new dimension to the numpy array. There are multiple ways of doing this as other answers mentioned np.expand_dims, np.new_axis, np.reshape etc. But I usually use the following as I find it the most readable, especially when you are working with vectorizing multiple tensors and complex operations involving broadcasting (check this Bounty question that I solved with this method).

x[:,:,None].shape

(2,3,1)
x[None,:,None,:,None].shape

(1,2,1,3,1)
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

Well, maybe this is an overkill for the array you have, but definitely the most efficient solution is to use np.lib.stride_tricks.as_strided. This way no data is copied.

import numpy as np
x = np.array([[1., 2., 3.], [4., 5., 6.]])

newshape = x.shape[:-1] + (x.shape[-1], 1)
newstrides = x.strides + x.strides[-1:]
a = np.lib.stride_tricks.as_strided(x, shape=newshape, strides=newstrides)

results in:

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

       [[4.],
        [5.],
        [6.]]])
>>> a.shape
(2, 3, 1)
Péter Leéh
  • 2,069
  • 2
  • 10
  • 23