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?
2
  • What do you mean by "without creating a copy of the data?" Commented Oct 23, 2014 at 8:38
  • @Ffisegydd I do not want the data to be copied in memory. Rather I want numpy to use the same memory but interpret it differently. Commented Oct 23, 2014 at 11:01

2 Answers 2

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

If I run this code, a is not contiguous and it also appears that the data is copied...
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

2 Comments

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 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).

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.