0

Suppose I have the following numpy array:

a = np.array([[1, 1, 0, 0, 1],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 1],
       [1, 1, 0, 0, 0],
       [1, 1, 0, 0, 0],
       [1, 1, 0, 0, 0],
       [0, 0, 0, 1, 0],
       [1, 1, 0, 0, 0],
       [1, 1, 0, 0, 0],
       [1, 1, 1, 0, 1],
       [1, 1, 0, 0, 0],
       [1, 1, 0, 0, 1],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0],
       [1, 0, 1, 1, 0]])

I want to select only the rows, where column with index 1 have value 1 and column with index 2 have value 0.

i tried the following:

evidence = {1:1,2:0}
mask = a[:,list(evidence.keys())] == list(evidence.values())

But after that i am stuck. how can I do it in numpy 2-D array?

1 Answer 1

1

Try:

out = a[(a[:, 1] == 1) & (a[:, 2] == 0)]

Given a dictionary of column, value pairs, you could use:

evidence = {1:1,2:0}
out = a[ np.logical_and.reduce([a[:, c] == v for c, v in evidence.items()]) ]

which generalizes the above solution to a sequence of &.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer! this works, how can it be done in general(for n columns)? For example if I have a dictionary with n key_value pairs?
See the edited solution. The evidence being a dictionary feels a bit awkward to me though. If that is something you can change, I would

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.