Explain numpy.ravel and numpy.flattern in Python

In this article, we are going to see about the two hand in hand functions, namely numpy.ravel and numpy.flatten.

Let’s talk about numpy.ravel:

numpy.ravel(arr,order)

This function takes two arguments namely arr and order.

It returns the contiguous flattened version of the given array. The argument order is an optional argument which means that you need not give the value for it. by default it is order=’C’. Let’s see other possibilities of the argument order. Basically this argument order tells the function to how to read ex: row-major, column-major e.t.c;

C  means row-major like how we use in programs or default. You might get it wrong as C is for column-major but it is for C-style of reading.

F means it reads the array as column-major. which means if you meant to give a matrix m but it reads as m’ (read as m-Transpose). There exist other possible values too for that extra information kindly check for NumPy documentation.

Let’s see an example.

import numpy as np
a = [[1,2,3,4,5],
     [6,7,8,9,10]]

np_a = np.array(a)
print("This is with default row-major order")
print(np.ravel(np_a))
print("Column-major order")
print(np.ravel(np_a,order='F'))
print("Making multi-dimensional to contiguous")
multi = [[[1,2],[5,6]],
        [[7,8],[3,4]]]

np_multi  = np.array(multi)
print(np.ravel(np_multi))
OUTPUT:
This is with default row-major order
[ 1  2  3  4  5  6  7  8  9 10]
Column-major order
[ 1  6  2  7  3  8  4  9  5 10]
Making multi-dimensional to contiguous
[1 2 5 6 7 8 3 4]

Let’s take a look at Flatten:

np.ndarray.flatten()

takes only one argument which is order same as for ravel

It does similar work but there are some differences. Let’s see how code would be

print(np_a.flatten())
print(np_multi.flatten('F'))
OUTPUT:
[ 1  2  3  4  5  6  7  8  9 10]
[1 7 5 3 2 8 6 4]

The biggest difference is that flatten was called on a NumPy ndarray object. Whereas in ravel it is a library function and can be called upon an object (no need to be a ndarray object only). Let’s see the following code.

print(np.ravel([[1,2,3],[4,5,6]]))
#print(np.flatten([[1,2,3],[4,5,6]]))
OUTPUT:
[1 2 3 4 5 6]

The highlighted code (second line)should be commented on since it is an error. Here in the above code, we called ravel up on a normal list rather than a NumPy object so it is a library level function. Whereas flatten will work only on ndarray.

 

Leave a Reply

Your email address will not be published. Required fields are marked *