Stéphane Darbois
Stéphane Darbois

Reputation: 15

Remove specific values from numpy array without loops

I have the following numpy arrays:

# doors = [[0,1,2],[0,1,2],....,[0,1,2]
doors = np.broadcast_to(np.array([0, 1, 2]),(max_samples, 3))
# first_choice = [ [2],[1],....,[2] ]
first_choice = np.random.randint(3, size=(max_samples, 1))

Without using any kind of loops (for, while, etc.) i would like to create a new numpy array called result who contains doors with suppressed first choice.

Example:

first_choice = [ [2], [1], [1], [0] ....]
result = [ [0,1],[0,2],[0,2],[1,2] .....]

How can i do that ? Use of any libraries if accepted if necessary, i think numpy can do that request but don't know how.

Upvotes: 0

Views: 135

Answers (1)

javidcf
javidcf

Reputation: 59731

Here is one possibility:

import numpy as np

max_samples = 10
np.random.seed(100)
doors = np.broadcast_to(np.array([0, 1, 2]),(max_samples, 3))
first_choice = np.random.randint(3, size=(max_samples, 1))
print(first_choice[:, 0])
# [0 0 0 2 2 0 2 1 2 2]
# Take non-matches and reshape
result = doors[doors != first_choice].reshape((-1, 2))
print(result)
# [[1 2]
#  [1 2]
#  [1 2]
#  [0 1]
#  [0 1]
#  [1 2]
#  [0 1]
#  [0 2]
#  [0 1]
#  [0 1]]

Obviously for this to work each value in first_choice must be present once (and only once) in each corresponding row of doors.

Upvotes: 1

Related Questions