Slarty
Slarty

Reputation: 103

How best to randomly select a number of non zero elements from an array with many duplicate integers

I need to randomly select x non-zero integers from an unsorted 1D numpy array containing y integer elements including an unknown number of zeros as well as duplicate integers. The output should include duplicate integers if required by this random selection. What is the best way to achieve this?

Upvotes: 0

Views: 528

Answers (1)

Andre
Andre

Reputation: 788

One option is to select the non-zero elements first then use random.choice() (with the replace parameter set to either True or False) to select a given number of elements.

Something like this:

import numpy as np
rng = np.random.default_rng() # doing this is recommended by numpy

n = 4 # number of non-zero samples

arr = np.array([1,2,0,0,4,2,3,0,0,4,2,1])
non_zero_arr = arr[arr!=0]

rng.choice(non_zero_arr, n, replace=True)

Upvotes: 1

Related Questions