1

Suppose I have the following numpy array of strings:

a = numpy.array(['apples', 'foobar', ‘bananas’, 'cowboy'])

I would like to generate len(a)/2 random pairs of strings from that matrix in another numpy matrix without repeating elements in each pair, with unique pairs and also with unique values for each pair (each value is unique for each pair). I also need to fix the random number generator so the pairs are always the same no matter how many times the algorithm is run. Is it possible to do that?

1 Answer 1

2

numpy.random.choice

The random.choice method is probably going to achieve what you're after.

import numpy as np

n_samples = 2

# Set the random state to the same value each time,
# this ensures the pseudorandom array that's generated is the same each time.
random_state = 42
np.random.seed(random_state)


a = np.array(['apples', 'foobar', ‘bananas’, 'cowboy'])

new_a = np.random.choice(a, (2, n_samples), replace=False)

The replace=False ensures that an element is only used once, which would produce the following output.

array([['foobar', 'cowboy'],
       ['bananas', 'apples']], dtype='<U7')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.