Python 如何使用索引和值迭代 1d NumPy 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49384682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:04:34  来源:igfitidea点击:

How to iterate 1d NumPy array with index and value

pythonarraysnumpyindexingiterator

提问by user40780

For python dict, I could use iteritems()to loop through key and value at the same time. But I cannot find such functionality for NumPy array. I have to manually track idxlike this:

对于 python dict,我可以使用iteritems()同时循环遍历键和值。但是我找不到 NumPy 数组的这种功能。我必须idx像这样手动跟踪:

idx = 0 
for j in theta:
   some_function(idx,j,theta)
   idx += 1

Is there a better way to do this?

有一个更好的方法吗?

回答by jpp

There are a few alternatives. The below assumes you are iterating over a 1d NumPy array.

有几种选择。下面假设您正在迭代一维 NumPy 数组。

Iterate with range

迭代 range

for j in range(theta.shape[0]):  # or range(len(theta))
   some_function(j, theta[j], theta)

Note this is the onlyof the 3 solutions which will work with numba. This is noteworthy since iterating over a NumPy array explicitly is usually only efficient when combined with numbaor another means of pre-compilation.

请注意,这是3 种解决方案中唯一可以与numba. 这是值得注意的,因为显式迭代 NumPy 数组通常仅在与numba预编译或其他预编译方法结合使用时才有效。

Iterate with enumerate

迭代 enumerate

for idx, j in enumerate(theta):
   some_function(idx, j, theta)

The most efficient of the 3 solutions for 1d arrays. See benchmarking below.

1d 阵列的 3 种解决方案中最有效的。请参阅下面的基准测试。

Iterate with np.ndenumerate

迭代 np.ndenumerate

for idx, j in np.ndenumerate(theta):
   some_function(idx[0], j, theta)

Notice the additional indexing step in idx[0]. This is necessary since the index (like shape) of a 1d NumPy array is given as a singleton tuple. For a 1d array, np.ndenumerateis inefficient; its benefits only show for multi-dimensional arrays.

请注意 中的附加索引步骤idx[0]。这是必要的,因为shape1d NumPy 数组的索引(如)是作为单例元组给出的。对于一维数组,np.ndenumerate效率低下;它的好处只显示在多维数组中。

Performance benchmarking

性能基准测试

# Python 3.7, NumPy 1.14.3

np.random.seed(0)

arr = np.random.random(10**6)

def enumerater(arr):
    for index, value in enumerate(arr):
        index, value
        pass

def ranger(arr):
    for index in range(len(arr)):
        index, arr[index]
        pass

def ndenumerater(arr):
    for index, value in np.ndenumerate(arr):
        index[0], value
        pass

%timeit enumerater(arr)    # 131 ms
%timeit ranger(arr)        # 171 ms
%timeit ndenumerater(arr)  # 579 ms

回答by sushmit

You can use numpy.ndenumeratefor example

你可以使用numpy.ndenumerate例如

import numpy as np
test_array = np.arange(2, 3, 0.1)
for index, value in np.ndenumerate(test_array):
    print(index[0], value)

For more information refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html

有关更多信息,请参阅https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html