0

Is it possible to convert a one dimensional array

a = np.array([1,2,3])

to a two dimensional array that is equivalent to

b = np.array([[1],[2],[3]])
  1. without creating a copy of the array and also
  2. with b being contiguous?
Woltan
  • 13,723
  • 15
  • 78
  • 104

2 Answers2

2

You can do this using np.newaxis and the T transpose method.

import numpy as np

a = np.array([1,2,3])

a = a[np.newaxis].T

print(a)
# [[1]
#  [2]
#  [3]]
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
1

Reshaping the array does not copy data (where possible*) and retains C contiguity (usually):

>>> a = np.array([1,2,3])
>>> b = a.reshape(3, 1)
>>> b
array([[1],
       [2],
       [3]])

>>> b.flags

  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

*Edit: Reshaping often creates a view of an array, but this is not always possible (docs). There are ways to check that the data has not been copied and that a and b share the same underlying data. For example see here and here.

In the above case, trying a couple of tests showed that reshape created a view of a (no data copied):

>>> a.data == b.data
True

>>> np.may_share_memory(a, b) # function from linked answer above
True
Community
  • 1
  • 1
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • I though about this very same solution. How do you know that the data is not copied? Doesn't `id(a) != id(b)` prove that the data is copied? – Woltan Oct 23 '14 at 09:25
  • @Woltan updated my answer slightly. Sharing data between arrays is not always easy to determine (the `id` test isn't reliable because of the fundamental differences between Python and NumPy objects). – Alex Riley Oct 23 '14 at 10:09