1

I have two arrays A and B as shown below:

A = [[ 1  2  3  4]
     [ 5  6  7  8]
     [ 9 10 11 12]
     [13 14 15 16]]

B = [3, 11]

Now I need the values in the 4th column of A for rows having values in B and 3rd column of A matching. For this particular case the output array C should be:

C = [4, 12]

I tried this, using the following code, but it returns an empty array:

import numpy as np
A = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
B = np.array([3, 11])
C = A[np.where(B[:] == A[:][2]), 3]
print(C)

2 Answers 2

1

You can use numpy.in1d to check which of the items from B match with items in A's third column.

>>> np.in1d(A[:, 2], B)
array([ True, False,  True, False], dtype=bool)

Now using this boolean array simply index A's fourth column:

>>> A[:,3][np.in1d(A[:, 2], B)]
array([ 4, 12])
Sign up to request clarification or add additional context in comments.

Comments

1

Here's a pure Python implementation, if that's okay:

>>> A = [[ 1,  2,  3,  4], [ 5,  6,  7,  8], [ 9, 10, 11, 12], [13, 14, 15, 16]]
>>> B = [3,11]
>>> C = [l[3] for l in A if l[2] in B]
>>> C
[4, 12]

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.