Tobias Stein -4 years ago 86
Python Question

# Loop over array and get more than one dimension with indexing

Referring to my previous (solved) question here (link), I now want to do that operation on a multidimensional array.

``````vertices = [[ 1.25, 4.321, -4], [2, -5, 3.32], [23.3, 43, 12], [32, 4, -23]]

newedges = [[1, 3, 2, 0], [2, 1, 3, 0], [1, 2, 0, 3]]

newresult = [[[2, -5, 3.32], [32, 4, -23], [23.3, 43, 12], [ 1.25, 4.321, -4]], [[23.3, 43, 12], [2, -5, 3.32], [32, 4, -23], [ 1.25, 4.321, -4]], [[2, -5, 3.32], [23.3, 43, 12], [ 1.25, 4.321, -4], [32, 4, -23]]]
``````

I want to get back an array with the same shape as "newedges" but with the indexes replaced by the vertices (-> newresult).

I tried:

``````list = ()
arr = np.ndarray(newedges.shape[0])

for idx, element in enumerate(newedges):

arr[idx] = vertices[newedges[idx]]

list.append(arr)
``````

But get an index error (with my real data, that's why there is an index 61441):

``````IndexError: index 61441 is out of bounds for axis 1 with size 2
``````

Here you go:

``````import numpy as np

vertices = [[ 1.25, 4.321, -4], [2, -5, 3.32], [23.3, 43, 12], [32, 4, -23]]
vertices= np.array(vertices)
newedges = [[1, 3, 2, 0], [2, 1, 3, 0], [1, 2, 0, 3]]

newresult = []

for edgeset in newedges:
updatededges = np.take(vertices, edgeset, 0)
newresult.append(updatededges)

print newresult
"""
newresult = [array([[  2.   ,  -5.   ,   3.32 ],
[ 32.   ,   4.   , -23.   ],
[ 23.3  ,  43.   ,  12.   ],
[  1.25 ,   4.321,  -4.   ]]),

array([[ 23.3  ,  43.   ,  12.   ],
[  2.   ,  -5.   ,   3.32 ],
[ 32.   ,   4.   , -23.   ],
[  1.25 ,   4.321,  -4.   ]]),

array([[  2.   ,  -5.   ,   3.32 ],
[ 23.3  ,  43.   ,  12.   ],
[  1.25 ,   4.321,  -4.   ],
[ 32.   ,   4.   , -23.   ]])]
"""
``````

Another advice: do not use python keywords like `list` as variable names. This goes for any programming language

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download