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]])
- without creating a copy of the array and also
- with
b
being contiguous?
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]])
b
being contiguous?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]]
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