ksm001
ksm001

Reputation: 4022

Transform an array of shape (n,) to a numpy array of shape (n,1)

I have an array that I read from a .npz file with numpy, that has a shape I can not really explain.

When I print the array I get numbers in the following form:

[1 2 3 2 1 8 9 8 3 4 ...]

without any comma separating them

I would like to transform this array into a numpy array of dimensions (n,1) where n is the number of elements and 1 is the number of columns.

Is there an elegant way of doing it?

Upvotes: 4

Views: 4068

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90899

The shape (n, ) means its a one-dimensional array of n length . If you think the shape (n, 1) represents a one-dimensional array, then it does not, (n,1) represents a two dimensional array of n sub-arrays, with each sub-array having 1 element.

If what you really want is an array of shape (n, 1), you can use ndarray.reshape() with shape (-1, 1) -

array.reshape((-1,1))

Demo -

In [64]: na
Out[64]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [65]: str(na)
Out[65]: '[0 1 2 3 4 5 6 7 8 9]'

In [66]: na.reshape((-1,1))
Out[66]:
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

In [67]: na.reshape((-1,1)).shape
Out[67]: (10, 1)

As you can see this moves the array from being a 1d array to a 2d array with each inner row (inner array) containing only 1 element. This may not be what you want. The output like -

[1 2 3 2 1 8 9 8 3 4 ...]

is just the str() result of a numpy array, it does mean the elements internally are not separated.

Upvotes: 7

Related Questions