196

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([[1], [2], [3], [4]]), I want to get A = array([1,2,3,4]).

To achieve it, I use A = np.array(M.T)[0]. Does anyone know a more elegant way to get the same result?

Thanks!

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
yassin
  • 6,529
  • 7
  • 34
  • 39
  • Ivnerse question: [convert a 2D numpy array to a 2D numpy matrix](http://stackoverflow.com/questions/17443620/convert-a-2d-numpy-array-to-a-2d-numpy-matrix) – Tobias Kienzler Jul 03 '13 at 08:56

10 Answers10

238

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.

Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • 17
    Little rant on my part...why does numpy have arrays and matrices as separate entities. It is so unpythonic IMHO. Thanks for this tip @Joe. – Naijaba Feb 13 '15 at 06:37
  • 9
    @Naijaba - For what it's worth, the matrix class is effectively (but not formally) depreciated. It's there mostly for historical purposes. Removing `numpy.matrix` is a bit of a contentious issue, but the numpy devs very much agree with you that having both is unpythonic and annoying for a whole host of reasons. However, the amount of old, unmaintained code "in the wild" that uses `matrix` makes it difficult to fully remove it. – Joe Kington Feb 13 '15 at 14:03
  • 1
    Not to mention, true matrix multiplication was only added for arrays in Numpy 1.10, and is basically still in beta. This means that a lot of people (including myself) still have to use matrices instead of arrays to get done what we want done. https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.html – Georges Oates Larsen Dec 31 '16 at 02:35
  • 2
    Sparse matrices are fundamental for memory-efficient machine learning (e.g., `sklearn`). In fact there are different `sparse matrix` types in `scipy`, which allow efficient access via rows or columns. I imagine this may be an issue for merging the concepts of matrix and array. That said, I'm wondering whether there could be introduced a `sparse array` type as well and whether there are any plans for doing that. Any clues? – pms Mar 04 '17 at 11:41
  • I think .flatten() works as well as .squeeze(), as long as you want a 1D array in the end. – wordsforthewise Dec 09 '17 at 03:35
  • array(..) defaults copy=True, so A and M are distinct if that's what you want [[ "asarray" behaves identically for matrix subclass ]] *see @hpaulj* M.A1 same as np.ravel(M) which returns a view of M in A, shared memory - more appropriate for large matrices – jayprich May 05 '18 at 23:19
149
result = M.A1

https://numpy.org/doc/stable/reference/generated/numpy.matrix.A1.html

matrix.A1
1-d base array
Ferro
  • 1,863
  • 2
  • 14
  • 20
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • 8
    I think this answer is better than the accepted answer, performance-wise, and simplicity – dariush May 20 '16 at 16:34
  • M.A1 is great, same implementation as "ravel" and "flatten" and in this case doesn't cause any data copy A thus remains linked to M which can cause surprises if A and/or M are mutable. M.flat genuine alternative returning "flatiter" generator (read-only semantics) np.squeeze(M) # gives a view removing dimensions of size 1, ok here too but not guaranteed to be 1-d for general M np.reshape(M,-1) # is usually a view depending on shape compatibility, this "-1" is a roundabout way to do A1/ravel/flatten – jayprich May 05 '18 at 23:07
13
A, = np.array(M.T)

depends what you mean by elegance i suppose but thats what i would do

John Conde
  • 217,595
  • 99
  • 455
  • 496
mvu
  • 131
  • 1
  • 2
13

You can try the following variant:

result=np.array(M).flatten()
bubble
  • 1,634
  • 12
  • 17
9
np.array(M).ravel()

If you care for speed; But if you care for memory:

np.asarray(M).ravel()
Kevad
  • 91
  • 1
  • 1
6

Or you could try to avoid some temps with

A = M.view(np.ndarray)
A.shape = -1
Pierre GM
  • 19,809
  • 3
  • 56
  • 67
2

First, Mv = numpy.asarray(M.T), which gives you a 4x1 but 2D array.

Then, perform A = Mv[0,:], which gives you what you want. You could put them together, as numpy.asarray(M.T)[0,:].

oracleyue
  • 394
  • 2
  • 9
2

This will convert the matrix into array

A = np.ravel(M).T
Siraj S.
  • 3,481
  • 3
  • 34
  • 48
2

ravel() and flatten() functions from numpy are two techniques that I would try here. I will like to add to the posts made by Joe, Siraj, bubble and Kevad.

Ravel:

A = M.ravel()
print A, A.shape
>>> [1 2 3 4] (4,)

Flatten:

M = np.array([[1], [2], [3], [4]])
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.ravel().

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.

numpy.squeeze() and M.reshape(-1) are slower than numpy.flatten() and numpy.ravel().

%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
Siddharth Satpathy
  • 2,737
  • 4
  • 29
  • 52
-1

Came in a little late, hope this helps someone,

np.array(M.flat)
Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95