2

I have following arrays.

In [1]: a = np.array([["aa", "bb", "cc"], ["cc", "bb", "aa"]])
In [2]: a
Out[2]:
array([['aa', 'bb', 'cc'],
       ['cc', 'bb', 'aa']],
       dtype='|S2')

In [3]: b = np.array([[11, 12, 13], [21, 22, 23]])
In [4]: b
Out[4]:
array([[11, 12, 13],
       [21, 22, 23]])

Relation between a and b can be described conceptually as b[0].aa = 11 b[0].bb = 12. b[0].cc = 13. i.e. row in 'a' are keys and row in 'b' are values of a single dict. First rows will represent

{'aa': 11, 'bb': 12, 'cc': 13}

Now we are given with keys of these dicts.

In [5]: c = np.array(["bb", "aa"])
In [6]: c
Out[6]:
array(['bb', 'aa'],
  dtype='|S2')

Now, what is the best way of accessing b array given 'c' which will give axis of each row as value in 'a'. One way to do is

In [7]: cond_list = [a[:, 0] == c,  a[:, 1] == c, a[:, 2] == c]
In [8]: choice_list = [b[:, 0],  b[:, 1], b[:, 2]]
In [9]: np.select(cond_list, choice_list)
Out[9]: array([12, 23])

Is there a better way of doing it? What if number of axis in a and b are not known before hand?

1 Answer 1

2
In [13]: a==c[:,np.newaxis]
Out[13]: 
array([[False,  True, False],
       [False, False,  True]], dtype=bool)

In [14]: b[a==c[:,np.newaxis]]
Out[14]: array([12, 23])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.