4

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?

1
  • The lack of commas is not significant. That's just how numpy prints arrays (with the str formatting). Use repr formatting if you want to see commas. Commented Sep 22, 2015 at 17:25

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

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.