Minimal example:
import numpy as np
list1 = [1,3,5,7]
list2 = [3,6,9,4]
list3 = [6,5,3,2]
arr = np.random.rand(72,22,22)
pos_list = np.vstack([list1, list2, list3]).T
print(pos_list)
arr[pos_list[0][0], pos_list[0][1], pos_list[0][2]]
for i in pos_list:
print(arr[i[0], i[1], i[2]])
My co-worker and I are attempting to increase the efficiency of the above point selection. There are many very large matrices generated and from these matrices, there are many specific points that must be pulled out.
In the above code, the first point that gets selected is (list1[0], list2[0], list3[0]). This continues on until the end of the (much larger) lists is reached.
Is there a vectorized approach to this-a way to avoid using for-loops-as this particular operation must be performed many times? Or pretty much any way that is more efficient than the above for-loop?
CodePudding user response:
I believe this does what you want, see also here:
pos_array = np.array(pos_list)
arr[pos_array[:,0], pos_array[:,1],pos_array[:,2]]
Output:
array([0.10539037, 0.17852727, 0.18794522, 0.04191294])
Or, you could also create an array of your lists directly, skipping the vstack
and the transposing:
import numpy as np
list1 = [1,3,5,7]
list2 = [3,6,9,4]
list3 = [6,5,3,2]
pos_array = np.array([list1,list2,list3])
arr = np.random.rand(72,22,22)
arr[pos_array[0], pos_array[1], pos_array[2]]
Output:
array([0.10539037, 0.17852727, 0.18794522, 0.04191294])