Python – Randomly select a piece of numbers from a numpy array

Randomly select a piece of numbers from a numpy array… here is a solution to the problem.

Randomly select a piece of numbers from a numpy array

I have a lot of data files, each containing a large number of data points.

After loading the file with numpy, I get a numpy array:

f=np.loadtxt("...-1.txt")

How to randomly select the length x, but the order of the numbers cannot be changed?

For example:

f = [1,5,3,7,4,8]

If I want to select 3 data points of random length, the output should be:

  1. 1, 5, 3 or
  2. 3, 7, 4 or
  3. 5, 3, 7, etc

Solution

Pure logic will get you there.

For list f and maximum length x, the valid starting point for random slices is limited to 0, len(f)-x:

     0 1 2 3
f = [1,5,3,7,4,8]

So all valid starting points can be selected with random.randrange(len(f)-x+1) (+1 because randrange effectively like range).

Store the random starting point in the variable start and slice the array using [start:start+x], or get creative and use another slice after the first slice:

result = f[random.randrange(len(f)-x+1):][:3]

Related Problems and Solutions