如何使用索引和值迭代 1d NumPy 数组 [英] How to iterate 1d NumPy array with index and value

查看:28
本文介绍了如何使用索引和值迭代 1d NumPy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 idx like this:

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

有没有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

有几个替代方案.下面假设您正在迭代一维 NumPy 数组.

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

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

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

Note this is the only of 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 numba or another means of pre-compilation.

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

最有效的 3 种一维数组解决方案.请参阅下面的基准测试.

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

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

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

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.ndenumerate is inefficient; its benefits only show for multi-dimensional arrays.

# 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

这篇关于如何使用索引和值迭代 1d NumPy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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