I've come across some code where the use of numpy.ravel() is resulting in a 2D array - I've had a look at the documentation, which says that ravel() returns a 1D array (see https://numpy.org/doc/stable/reference/generated/numpy.ravel.html).
Here's a code snippet that shows this:
def jumbo():
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
matrix = np.zeros((3,3))
matrix.ravel()[:] = my_list
return matrix
new_matrix = jumbo()
print(f"new matrix is:\n{new_matrix}")
I suppose part of what I'm asking is what is the function of the range specifier [:] here?
CodePudding user response:
What you did is assigned values at "raveled" matrix, wihtout actually saving ravel operation.
matrix = np.empty((3,3)) # created empty matrix
matrix.ravel() # created 1d view of matrix
matrix.ravel()[:] # indexing every element of matrix to make assignment possible (matrix is still in (3,3) shape)
matrix.ravel()[:] = my_list # assigned values.
if you want return to be 1D then return raveled array like this
def jumbo():
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
matrix = np.empty((3,3))
matrix.ravel()[:] = my_list
return matrix.ravel()
new_matrix = jumbo()
print(f"new matrix is:\n{new_matrix}")
CodePudding user response:
ravel
returns a view of the numpy array, thus when you do:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
matrix = np.zeros((3,3))
matrix.ravel()[:] = my_list
You are using the view as a way to index the matrix
as 1D, temporarily.
This enables here to set the values from a 1D list, but the underlying array remains 2D.
The matrix.ravel()[:]
is used to enable setting the data. You could also use 2 steps:
view = matrix.ravel()
view[:] = my_list
output:
array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
important note on the views
As @Stef nicely pointed out in the comments, this "trick" will only work for C-contiguous arrays, meaning you couldn't use ravel('F')
:
demonstration:
view1 = matrix.ravel()
view2 = matrix.ravel('F') # actually not a view!
id(matrix)
# 140406991308816
id(view1.base)
# 140406991308816
id(view2.base)
# 9497104 # different id, we have a copy!