-1

Given

a = np.array([1,2,3,4,5,6,7,8])
b = np.array(['a','b','c','d','e','f','g','h'])

c = np.array([1,1,1,4,4,4,8,8])

where a & b 'correspond' to each other, how can I use c to slice b to get d which 'corresponds' to c:

d = np.array(['a','a','a','d','d','d','h','h')]

I know how to do this by looping

for n in range(a.shape[0]):
    d[n] = b[np.argmax(a==c[n])]

but want to know if I can do this without loops.

Thanks in advance!

Daniel von Eschwege
  • 481
  • 1
  • 4
  • 10

1 Answers1

0

With the a that is just position+1 you can simply use

In [33]: b[c - 1]
Out[33]: array(['a', 'a', 'a', 'd', 'd', 'd', 'h', 'h'], dtype='<U1')

I'm tempted to leave it at that, since the a example isn't enough to distinguish it from the argmax approach.

But we can test all a against all c with:

In [36]: a[:,None]==c
Out[36]: 
array([[ True,  True,  True, False, False, False, False, False],
       [False, False, False, False, False, False, False, False],
       [False, False, False, False, False, False, False, False],
       [False, False, False,  True,  True,  True, False, False],
       [False, False, False, False, False, False, False, False],
       [False, False, False, False, False, False, False, False],
       [False, False, False, False, False, False, False, False],
       [False, False, False, False, False, False,  True,  True]])
In [37]: (a[:,None]==c).argmax(axis=0)
Out[37]: array([0, 0, 0, 3, 3, 3, 7, 7])
In [38]: b[_]
Out[38]: array(['a', 'a', 'a', 'd', 'd', 'd', 'h', 'h'], dtype='<U1')
hpaulj
  • 221,503
  • 14
  • 230
  • 353