2016-11-17 117 views
-1

我試圖訪問numpy 2D數組中的每個項目。循環遍歷numpy數組中的每個項目?

我已經習慣了這樣的事情在Python [...] [...] [...]]

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

,但現在,我有一個data_array = np.array(features)

如何以同樣的方式遍歷它?

+0

我們需要以幫助到更多細節。 –

+1

這是否包含在基本的numpy文檔中? – hpaulj

+0

您可以用相同的方式遍歷遍歷它。試試看看!然而,迭代2D數組完全違背了使用numpy的點,即高效的數組操作。例如,閱讀[本文檔頁面](https://docs.scipy.org/doc/numpy-1.10.1/user/whatisnumpy.html)。 – Praveen

回答

2

做一個小的二維數組和嵌套列表從中:

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 

作品只是同爲陣列

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

如果你想修改元素,現在都不是很好。但是對於所有這些元素的粗略迭代。

數組我可以很容易地把它同是一個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] 

一般來說最好是不迭代與陣列工作循環。我給了這些迭代例子來澄清一些混淆。

-1

如果要訪問numpy 2D數組要素中的項目,可以使用要素[row_index,column_index]。如果你想通過numpy的數組迭代,你可以只修改你的腳本

for row in data: 

    for col in data: 

     print(data[row, col]) 
+1

如果你像這樣迭代,那麼'row'是一個1d數組。你可以用它作爲'data'的索引。第二次迭代也是一樣的。你可能已經'排成一行了:'記住。 – hpaulj

+0

你需要的是'data.shape [0]'中的行和'data.shape [1]中的col',或者'用於數據中的行:用於col中的行:print(col)'。 – Praveen

+0

是的,我忘了修改for循環來使用像Praveen那樣的行數和列數。 – shrubber

1

嘗試np.ndenumerate

>>> a =numpy.array([[1,2],[3,4]]) 
>>> for (i,j), value in np.ndenumerate(a): 
... print(i, j, value) 
... 
0 0 1 
0 1 2 
1 0 3 
1 1 4