循环遍历numpy数组中的每个项目? [英] Looping through each item in a numpy array?

查看:534
本文介绍了循环遍历numpy数组中的每个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问numpy二维数组中的每个项目.

I'm trying to access each item in a numpy 2D array.

我在Python [[...],[...],[...]]

I'm used to something like this in Python [[...], [...], [...]]

for row in data:
    for col in data:
       print(data[row][col])

但是现在,我有一个data_array = np.array(features)

我如何以相同的方式遍历它?

How can I iterate through it the same way?

推荐答案

制作一个小的2d数组,并从中嵌套一个列表:

Make a small 2d array, and a nested list from it:

In [241]: A=np.arange(6).reshape(2,3)
In [242]: alist= A.tolist()
In [243]: alist
Out[243]: [[0, 1, 2], [3, 4, 5]]

一种迭代列表的方法:

In [244]: for row in alist:
     ...:     for item in row:
     ...:         print(item)
     ...:         
0
1
2
3
4
5

在数组上的工作原理相同

works just same for the array

In [245]: for row in A:
     ...:     for item in row:
     ...:         print(item)
     ...:         
0
1
2
3
4
5

现在,如果要修改元素,两者都不是一件好事.但是,对于所有元素的粗略迭代,这是可行的.

Now neither is good if you want to modify elements. But for crude iteration over all elements this works.

在我可以轻松处理的阵列中,它是一个1d

WIth the array I can easily treat it was a 1d

In [246]: [i for i in A.flat]
Out[246]: [0, 1, 2, 3, 4, 5]

我还可以迭代嵌套索引

In [247]: [A[i,j] for i in range(A.shape[0]) for j in range(A.shape[1])]
Out[247]: [0, 1, 2, 3, 4, 5]

通常,最好使用没有迭代的数组.我给出了这些迭代示例,以消除一些混乱.

In general it is better to work with arrays without iteration. I give these iteration examples to clearup some confusion.

这篇关于循环遍历numpy数组中的每个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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