How to flatten axes of a multidimensional array without making copies in NumPy?
indexing, multidimensional-array, numpy, python
Solution
`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.
Problem
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.