简体   繁体   English

numpy.ravel 给出二维数组 - 谁能解释一下?

[英]numpy.ravel giving 2D array - can anyone explain?

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 ).我遇到了一些代码,其中使用 numpy.ravel() 会产生一个二维数组 - 我看过文档,它说 ravel() 返回一个一维数组(参见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?我想我要问的部分内容是范围说明符 [:] 的功能是什么?

ravel returns a view of the numpy array, thus when you do: ravel返回 numpy 数组的视图,因此当你这样做时:

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 .您正在使用视图作为暂时matrix索引为 1D 的一种方式。

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. matrix.ravel()[:]用于启用设置数据。 You could also use 2 steps:您还可以使用 2 个步骤:

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') :正如@Stef 在评论中很好地指出的那样,这个“技巧”只适用于 C-contiguous arrays ,这意味着你不能使用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!

What you did is assigned values at "raveled" matrix, wihtout actually saving ravel operation.您所做的是在“raveled”矩阵中分配值,而实际上没有保存 ravel 操作。

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如果你想返回 1D 然后像这样返回 raveled 数组

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}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM