简体   繁体   中英

Get element from array based on list of indices

z = np.arange(15).reshape(3,5)
indexx = [0,2]
indexy = [1,2,3,4]

zz = []
for i in indexx:
  for j in indexy:
    zz.append(z[i][j])

Output:

zz >> [1, 2, 3, 4, 11, 12, 13, 14]

This essentially flattens the array but only keeping the elements that have indicies present in the two indices list.

This works, but it is very slow for larger arrays/list of indicies. Is there a way to speed this up using numpy?

Thanks.

Edited to show desired output.

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.intersection(y) 

print(z)

z => apples

If I understand you correctly, just use Python set. And then cast it to list.

A list of integers can be used to access the entries of interest for numpy arrays.

z[indexx][:,indexy].flatten()

Indexing in several dimensions at once requires broadcasting the indices against each other. np.ix_ is a handy tool for doing this:

In [127]: z
Out[127]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
In [128]: z[np.ix_(indexx, indexy)]
Out[128]: 
array([[ 1,  2,  3,  4],
       [11, 12, 13, 14]])

Converting that to 1d is a trivial ravel() task.

Look at the ix_ produces, here it's a (2,1) and (1,4) array. You can construct such arrays 'from-scratch':

In [129]: np.ix_(indexx, indexy)
Out[129]: 
(array([[0],
        [2]]),
 array([[1, 2, 3, 4]]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM