Question

I have numpy array called data of dimensions 150x4 I want to create a new numpy array called mean of dimensions 3x4 by choosing random elements from data.

My current implementation is:

    cols = (data.shape[1])
    K=3
    mean = np.zeros((K,cols))
    for row in range(K):
        index = np.random.randint(data.shape[0])
        for col in range(cols):
            mean[row][col] = data[index][col]

Is there a faster way to do the same?

Was it helpful?

Solution

You can specify the number of random integers in numpy.randint (third argument). Also, you should be familiar with numpy.array's index notations. Here, you can access all the elements in one row by : specifier.

mean = data[np.random.randint(0,len(data),3),:]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top