2013-10-30 27 views
3

我正在處理來自netcdf文件的數據,其中有多維變量,讀入numpy數組。我需要掃描所有維度的所有值(座標軸)並更改一些值。但是,我不知道任何給定變量的維數。在運行時,我可以獲得numpy數組的ndims和形狀。 如何在不知道尺寸數量或形狀的情況下通過所有值編程循環?如果我知道一個變量是正好2個維度,我會做當事先不知道ndims時處理多維數組

shp=myarray.shape 
for i in range(shp[0]): 
    for j in range(shp[1]): 
    do_something(myarray[i][j]) 

回答

3

你應該看看ravelnditerndindex

# For the simple case 
for value in np.nditer(a): 
    do_something_with(value) 

# This is similar to above 
for value in a.ravel(): 
    do_somting_with(value) 

# Or if you need the index 
for idx in np.ndindex(a.shape): 
    a[idx] = do_something_with(a[idx]) 

在一個不相關的音符,numpy的陣列索引a[i, j]而不是a[i][j]。 python a[i, j]相當於用元組索引,即a[(i, j)]

+0

謝謝,你讓我走上正軌。我將最終使用ndenumerate。 – Micha

1

這可能是最簡單的遞歸:

a = numpy.array(range(30)).reshape(5, 3, 2) 

def recursive_do_something(array): 
    if len(array.shape) == 1: 
     for obj in array: 
      do_something(obj) 
    else: 
     for subarray in array: 
      recursive_do_something(subarray) 

recursive_do_something(a) 

如果您想索引:

a = numpy.array(range(30)).reshape(5, 3, 2) 

def do_something(x, indices): 
    print(indices, x) 

def recursive_do_something(array, indices=None): 
    indices = indices or [] 
    if len(array.shape) == 1: 
     for obj in array: 
      do_something(obj, indices) 
    else: 
     for i, subarray in enumerate(array): 
      recursive_do_something(subarray, indices + [i]) 

recursive_do_something(a) 
+0

如果你想要索引和值,你可以簡單地使用['ndenumerate'](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html)。 – DSM

+0

謝謝你的建議,我不知道numpy有一個特定的ndarray's枚舉員。 – Noctua

+0

好的方法!起初我確定遞歸會適用,但是我沒有深入。 – Micha

3

線的東西你可以用numpy的陣列的flat財產,它在所有值上返回一個發生器(不管形狀如何)。

例如:

>>> A = np.array([[1,2,3],[4,5,6]]) 
>>> for x in A.flat: 
...  print x 
1 
2 
3 
4 
5 
6 

您還可以設置的值以相同的順序他們回來,例如像這樣:

>>> A.flat[:] = [x/2 if x % 2 == 0 else x for x in A.flat] 
>>> A 
array([[1, 1, 3], 
     [2, 5, 3]]) 

我不知道在哪個flat返回以任何方式保證元素(因爲它通過元素迭代,因爲它們是在內存中的順序,所以根據您的陣列約定你可能它總是一樣的,除非你真的是故意這樣做,但要小心......)

而且這將適用於任何維度。

** - 編輯 - **

爲了澄清我的意思通過「爲了不保證」,通過flat返回不改變元素的順序,但我認爲這將是不明智的依靠它適用於像row1 = A.flat[:N]這樣的東西,儘管它大部分時間都可以使用。

相關問題