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

查看:154
本文介绍了如何使用索引和值迭代一维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

有更好的方法吗?

推荐答案

有几种选择.下面假设您正在迭代1d 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)

请注意,这是与唯一的 ="http://numba.pydata.org/" rel ="noreferrer"> 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个1d阵列解决方案中效率最高的.请参阅下面的基准测试.

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]中的其他索引步骤.这是必需的,因为1d 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

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

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