import numpy as np
y = np.array(((1,2,3),(4,5,6),(7,8,9)))
OUTPUT:
print(y.flatten())
[1 2 3 4 5 6 7 8 9]
print(y.ravel())
[1 2 3 4 5 6 7 8 9]
Both function return the same list.
Then what is the need of two different functions performing same job.
As explained here a key difference is that:
For example ravel
will work on a list of ndarrays, while flatten
is not available for that type of object.
@IanH also points out important differences with memory handling in his answer.
Here is the correct namespace for the functions:
numpy.ndarray.flatten
numpy.ravel
Both functions return flattened 1D arrays pointing to the new memory structures.
import numpy
a = numpy.array([[1,2],[3,4]])
r = numpy.ravel(a)
f = numpy.ndarray.flatten(a)
print(id(a))
print(id(r))
print(id(f))
print(r)
print(f)
print("\nbase r:", r.base)
print("\nbase f:", f.base)
---returns---
140541099429760
140541099471056
140541099473216
[1 2 3 4]
[1 2 3 4]
base r: [[1 2]
[3 4]]
base f: None
In the upper example:
- the memory locations of the results are different,
- the results look the same
- flatten would return a copy
- ravel would return a view.
How we check if something is a copy?
Using the .base
attribute of the ndarray
. If it's a view, the base will be the original array; if it is a copy, the base will be None
.