anonymous
anonymous

Reputation: 23

How to randomly choose index from elements that are the same

In numpy, I have two arrays a and b where all entries are 1's or 0's, I do c = a != b, now I want to randomly choose an index from c that is true (meaning, an index where a and b disagree), how do I do this?

Upvotes: 1

Views: 43

Answers (2)

Sandro Massa
Sandro Massa

Reputation: 108

Quick and dirty way to achieve this:

import numpy as np

a = np.array([1,0,1,1,1,0,0,0,1])
b = np.array([0,1,1,1,0,0,1,0,1])
c = a != b
# Generating a list of indexes where your desired criteria is met
d = np.where(c)[0]
r = np.random.choice(d)

Upvotes: 0

Brad Solomon
Brad Solomon

Reputation: 40878

You can combine np.random.choice() with np.where().

Inputs:

>>> import numpy as np
>>> a = np.array([0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1])
>>> b = np.array([1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1])
>>> c =  a != b
>>> c
array([ True, False,  True, False, False,  True,  True,  True, False,
       False,  True, False])

Example:

>>> np.random.choice(np.where(c)[0], size=1).item()
7

Breakdown: first take the indices where c is True:

>>> np.where(c)[0]
array([ 0,  2,  5,  6,  7, 10])

Now pick one:

>>> np.random.choice(np.where(c)[0], size=1)
7

And lastly get the 0th value as a scalar with .item().

Upvotes: 2

Related Questions