anon01
anon01

Reputation: 11171

remove randomly chosen elements from array

How can I do the following in Python?

caveat: array x may have repeated values, xi, that nevertheless have different probabilities (p(x) actually depends on parameters I'm not showing), so I want to be sure to remove the "correct" one that was chosen, not just elements that share the same value xi.

My code thusfar:

import numpy as np

N = 5;
x = np.linspace(0,5,11)
pdf = np.exp(-x**2);
pdf = pdf/np.sum(pdf);

x_rand_sorted = np.random.choice(x,N,replace=False,p = pdf)

print 'x:',x
print 'first N random elements:', x_rand_sorted
print 'x without random elements = ??'

Upvotes: 1

Views: 2639

Answers (2)

anon01
anon01

Reputation: 11171

Outputs:

  • remaining values: x_remaining
  • N random elements: x_rand_vals
  • random element indices:randices

Example:

import numpy as np
N = 9;
n = 4;
x = np.linspace(0,2,N);
pdf = np.exp(-x**2);
pdf = pdf/np.sum(pdf);

#create mask, choose random indices from x according to pdf, set chosen indices to True:
indices = np.full(x.shape, False, bool)
randices = np.random.choice(np.arange(indices.shape[0]), n, replace = False,p = pdf)
indices[randices] = True

x_rand_vals = x[randices]
x_remaining = x[~indices]

np.set_printoptions(precision=3)
print 'original x:\t\t', x
print 'pdf array:\t\t', pdf
print 'random indices:\t\t',randices
print 'random values:\t\t',x_rand_vals
print 'remaining array:\t',x_remaining

(example output):

    original x:         [ 0.   0.2  0.4  0.6  0.8  1.   1.2  1.4  1.6  1.8  2. ]
    random indices:     [4 2 5]
    random values:      [ 0.8  0.4  1. ]
    remaining array:    [ 0.   0.2  0.6  1.2  1.4  1.6  1.8  2. ]

Upvotes: 1

hilberts_drinking_problem
hilberts_drinking_problem

Reputation: 11602

You can use a boolean mask:

import numpy as np

N = 5;
x = np.linspace(0,5,11)
pdf = np.exp(-x**2);
pdf = pdf/np.sum(pdf);

index = np.full(x.shape, False, bool)
index[np.random.choice(np.arange(index.shape[0]), N, replace = False,p = pdf)] = True

x_rand_sorted = x[index]
x_rand_remaining = x[~index]

print 'x:',x
print 'first N random elements:', x_rand_sorted
print 'x without random elements: ', x_rand_remaining

Upvotes: 1

Related Questions