Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rapid Selection of points from large numpy array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading