I am using numpy. I have a matrix with 1 column and N rows and I want to get an array from with N elements.
For example, if i have
M = matrix([, , , ]), I want to get
A = array([1,2,3,4]).
To achieve it, I use
A = np.array(M.T). Does anyone know a more elegant way to get the same result?
If you’d like something a bit more readable, you can do this:
A = np.squeeze(np.asarray(M))
Equivalently, you could also do:
A = np.asarray(M).reshape(-1), but that’s a bit less easy to read.
Or you could try to avoid some temps with
A = M.view(np.ndarray) A.shape = -1
A, = np.array(M.T)
depends what you mean by elegance i suppose but thats what i would do
You can try the following variant:
result = M.A1
matrix.A1 1-d base array
If you care for speed; But if you care for memory:
Mv = numpy.asarray(M.T), which gives you a 4×1 but 2D array.
A = Mv[0,:], which gives you what you want. You could put them together, as
This will convert the matrix into array
A = np.ravel(M).T
A = M.ravel() print A, A.shape >>> [1 2 3 4] (4,)
M = np.array([, , , ]) A = M.flatten() print A, A.shape >>> [1 2 3 4] (4,)
numpy.ravel() is faster, since it is a library level function which does not make any copy of the array. However, any change in array A will carry itself over to the original array M if you are using
numpy.flatten() is slower than
numpy.ravel(). But if you are using
numpy.flatten() to create A, then changes in A will not get carried over to the original array M.
M.reshape(-1) are slower than
%timeit M.ravel() >>> 1000000 loops, best of 3: 309 ns per loop %timeit M.flatten() >>> 1000000 loops, best of 3: 650 ns per loop %timeit M.reshape(-1) >>> 1000000 loops, best of 3: 755 ns per loop %timeit np.squeeze(M) >>> 1000000 loops, best of 3: 886 ns per loop
Came in a little late, hope this helps someone,