为什么NumPy高级索引对于列表列表和numpy数组会产生不同的结果? [英] Why does NumPy advanced indexing yield different results for list of lists and numpy array?

查看:56
本文介绍了为什么NumPy高级索引对于列表列表和numpy数组会产生不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对NumPy的高级索引有疑问.

I have a question about NumPy's advanced indexing.

我发现了这个问题,但我想我的问题会有所不同.

I found this question, but I guess my question is slightly different.

在下面的示例中,x_array是预期的结果.但是,当我尝试使用列表进行相同操作时,结果将有所不同.

In the example below x_array is the expected result. But when I tried the same with a list the result is different.

来自numpy文档:

From the numpy doc:

高级索引被触发时选择对象obj是一个 非元组序列对象,ndarray(数据类型为整数或布尔值), 或具有至少一个序列对象或ndarray(数据类型)的元组 整数或布尔值).有两种类型的高级索引:整数 和布尔值.

Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). There are two types of advanced indexing: integer and Boolean.

import numpy as np

vertices = np.arange(9).reshape((3,3))

idx_list = [[0, 1, 2],
            [0, 2, 1]]

x_list = vertices[idx_list]

print('list')

print(x_list)

#this works as expected
idx_array = np.array(idx_list)
x_array = vertices[idx_array]

print('array')
print(x_array)

idx_list应该触发高级索引,因为它是非元组序列对象"?还是这里的列表和元组相同,并且是具有至少一个序列对象的元组"

idx_list should trigger advanced indexing as it is a "non-tuple sequence object?" Or is a list and a tuple the same here and it is "a tuple with at least one sequence object"

使用列表所产生的效果与传递两个用方括号内的逗号分隔的列表条目(每个维度一个)相同.

Using the list yields the same as when passing the two list entries separated by a comma within the square brackets (one for each dimension).

x_list_2 = vertices[idx_list[0], idx_list[1]] 

这也是我期望的行为.

推荐答案

最后,它取决于 https: //stackoverflow.com/a/40599589/7919597

从numpy的索引文档中:

From numpy's indexing documentation:

为了保持与数字通用用法的向后兼容性, 如果选择对象是任何对象,也将启动基本切片 包含切片对象的非ndarray序列(例如列表), 省略号对象或newaxis对象,但不适用于整数数组或 其他嵌入序列.

In order to remain backward compatible with a common usage in Numeric, basic slicing is also initiated if the selection object is any non-ndarray sequence (such as a list) containing slice objects, the Ellipsis object, or the newaxis object, but not for integer arrays or other embedded sequences.

带有列表的示例触发了向后兼容性逻辑的未记录部分,如源代码中的注释所述:

The example with the list triggers an undocumented part of the backward compatibility logic, as described in a comment in the source code:

/*
 * Sequences < NPY_MAXDIMS with any slice objects
 * or newaxis, Ellipsis or other arrays or sequences
 * embedded, are considered equivalent to an indexing
 * tuple. (`a[[[1,2], [3,4]]] == a[[1,2], [3,4]]`)
 */

这篇关于为什么NumPy高级索引对于列表列表和numpy数组会产生不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆