I am wondering if there is a way to flatten a multidimensional array (i.e., of type ndarray
) along given axes without making copies in NumPy. For example, I have an array of 2D images and I wish to flatten each to a vector. So, one easy way to do it is numpy.array([im.flatten() for im in images])
, but that creates copies of each.
Asked
Active
Viewed 1.2k times
13

Alexandre Vassalotti
- 1,895
- 2
- 15
- 14
2 Answers
15
ravel
it:
>>> a = numpy.arange(25).reshape((5, 5))
>>> b = a.ravel()
>>> b[0] = 55
>>> a
array([[55, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
Or reshape
it:
>>> a = numpy.arange(27).reshape((3, 3, 3))
>>> b = a.reshape((9, 3))
>>> b[0] = 55
>>> a
array([[[55, 55, 55],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
Under most circumstances, these both return a view of the original array, rather than a copy.

senderle
- 145,869
- 36
- 209
- 233
-
Thank you! `reshape` did the trick for me. I thought before it would break the one-to-one mapping between my 2D matrices and vectors. But nope, it worked! – Alexandre Vassalotti Apr 07 '12 at 06:00
7
If you don't know the shape of your input array:
images.reshape((images.shape[0], -1))
-1
tells reshape to work out the remaining dimensions. This assumes that you
want to flatten the first axis of images.

aaren
- 5,325
- 6
- 29
- 24