samedi 7 octobre 2017

python: creating random matrix by excluding values

Assuming I have the following data:

data = [1,1,3,2,4]
max_value = 4 # it is known from before
number_of_random_values = 2

And what I want is to create random values with range between 1 and 4 for each point of data but excluding the case of the point for each case. To make it more clear here is an example:

data point    random_values
1          -> [2,4]
1          -> [3,2]
3          -> [1,4]
2          -> [3,1]
4          -> [1,3]

So what we have above is: for each data point two random values which these random numbers can not be the same as the data point. What I have done until now is the following:

desired_values = np.zeros((len(data), number_of_random_values))
range_of_data = range(1, max_value + 1)
i = 0
for data_point in data:
    copy_of_range = copy.copy(range_of_data)
    copy_of_range.remove(data_point)
    random_values_for_data_point = random.sample(copy_of_range, number_of_random_values)
    desired_values[i] = random_values_for_data_point
    i = i + 1

The above code does what I want (desired results in numpy array) but it is clear that it is not performance-wise optimized.

Is there a vectorized method to implement this?or something more efficient?




Aucun commentaire:

Enregistrer un commentaire