flatten() function we can flatten a matrix to one dimension in python. order:'C' means to flatten in row-major. 'F' means to flatten in column-major. 'A' means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.
flatten() function return a copy of the array collapsed into one dimension. Syntax : numpy.ndarray.flatten(order='C') Parameters : order : [{'C', 'F', 'A', 'K'}, optional] 'C' means to flatten in row-major (C-style) order.
flatten always returns a copy. ravel returns a view of the original array whenever possible. This isn't visible in the printed output, but if you modify the array returned by ravel, it may modify the entries in the original array. If you modify the entries in an array returned from flatten this will never happen.
You might need to check out numpy.flatten
and numpy.ravel
, both return a 1-d array from an n-d array.
Furthermore, if you're not going to modify the returned 1-d array, I suggest you use numpy.ravel
, since it doesn't make a copy of the array, but just return a view of the array, which is much faster than numpy.flatten
.
>>>a = np.arange(10000).reshape((100,100))
>>>%timeit a.flatten()
100000 loops, best of 3: 4.02 µs per loop
>>>%timeit a.ravel()
1000000 loops, best of 3: 412 ns per loop
Also check out this post.
You can use the reshape
method.
>>> import numpy
>>> b = numpy.array([[[1,2,3],[4,5,6]], [[10,11,12],[13,14,15]]])
>>> b.reshape([2, 6])
array([[ 1, 2, 3, 4, 5, 6],
[10, 11, 12, 13, 14, 15]])
How about:
>>> import numpy as np
>>> a=np.arange(1,7).reshape((2,3))
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> a.flatten()
array([1, 2, 3, 4, 5, 6])
and
>>> import numpy as np
>>> b=np.arange(1,13).reshape((2,2,3))
>>> b
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
>>> b.reshape((2,6))
array([[ 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With