用索引迭代numpy(相当于python枚举的numpy) [英] Iterate over numpy with index (numpy equivalent of python enumerate)

查看:83
本文介绍了用索引迭代numpy(相当于python枚举的numpy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数将计算多维numpy数组中元素之间的晶格距离(水平和垂直步数).为此,我需要遍历数组时从每个元素的索引中检索实际数字.我想将这些值存储为可以通过距离公式计算的数字.

I'm trying to create a function that will calculate the lattice distance (number of horizontal and vertical steps) between elements in a multi-dimensional numpy array. For this I need to retrieve the actual numbers from the indexes of each element as I iterate through the array. I want to store those values as numbers that I can run through a distance formula.

对于示例数组A

 A=np.array([[1,2,3],[4,5,6],[7,8,9]])

我想创建一个循环遍历每个元素的循环,并且对于第一个元素1,它将检索a = 0,b = 0,因为1位于A [0,0],则a = 0,b = 1表示元素2,因为它位于A [0,1],依此类推...

I'd like to create a loop that iterates through each element and for the first element 1 it would retrieve a=0, b=0 since 1 is at A[0,0], then a=0, b=1 for element 2 as it is located at A[0,1], and so on...

我的预期输出是数组中每个元素的两个数字(对应于该元素的两个索引值).因此,在上面的示例中,这就是我分配的两个值分别为a和b.我只需要在循环内检索这两个数字(而不是分别另存为另一个数据对象).

My envisioned output is two numbers (corresponding to the two index values for that element) for each element in the array. So in the example above, it would be the two values that I am assigning to be a and b. I only will need to retrieve these two numbers within the loop (rather than save separately as another data object).

任何关于如何执行此操作的想法将不胜感激!

Any thoughts on how to do this would be greatly appreciated!

推荐答案

您可以使用

You can iterate through the values in your array with numpy.ndenumerate to get the indices of the values in your array.

使用上面的文档:

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
for index, values in np.ndenumerate(A):
    print(index, values)  # operate here

这篇关于用索引迭代numpy(相当于python枚举的numpy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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