python - 如何将 numpy 的整数数组索引应用于 ndarray-s 和 python 列表?

标签 python arrays python-3.x numpy

Numpy 有 "integer array indexig" ,它允许使用其他 ndarray 或列表索引 ndarray:

>> A = np.arange(10,20)
>> A[[1,2,3]]
Out[14]: array([11, 12, 13])

假设我不知道A是什么,它可以是ndarray或Python的列表。

numpy 中是否有任何显式索引函数,它允许相同的索引并接受两种类型?

例如:

>> A = np.arange(10,20)
>> np.get_elements(A, [1,2,3])
Out[14]: array([11, 12, 13])
>> A = range(10,20)
>> np.get_elements(A, [1,2,3])
Out[15]: [11, 12, 13]

最佳答案

def get_elements(A, idx):
    try:
        return A[idx]
    except TypeError:
        import operator
        return list(operator.itemgetter(*idx)(A))

In [35]: get_elements(np.arange(10), [1,3,4])
Out[35]: array([1, 3, 4])
In [36]: get_elements(np.arange(10).tolist(), [1,3,4])
Out[36]: [1, 3, 4]

itemgetter 只是一个便利类。列表理解也同样好

In [39]: [A[i] for i in [1,3,4]]
Out[39]: [1, 3, 4]

take 这样的 numpy 函数返回一个数组

In [40]: np.take(A,[1,3,4])
Out[40]: array([1, 3, 4])

如果需要,可以将其转换回列表。

关于python - 如何将 numpy 的整数数组索引应用于 ndarray-s 和 python 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47393056/

相关文章:

c# - 根据另一个数组中指定的索引从数组中选择元素c#

algorithm - 如何按每个数字出现频率的降序排列数组?

python - 用 Python 3 编写 Cocoa 应用程序

python - 如何使用python检查一个值是否在另一个值的10以内

python - 名称错误 : name '__main__' is not defined

python - 替换边缘上的数字

python - 使用连接字符串过滤 pandas 数据框中的行

php - 配置 eclipse

c - C 中没有上边界的数组

python - 在Python中从数据库查询中读取并显示文本文件中的数据