Select floats in different multidimentional arrays using python

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Select floats in different multidimentional arrays using python on this date .

I have different multidimensional arrays, for example:

[[0, 3, 7, 2], [7, -1.3, 4, 0.2], [3.1, 3, -1, -1]]

[[[0, 1], [3, 4]], [[7, 3.142], [-2.71, 1.8]]]

And I would like to randomize a certain amount of the floats contained in the different arrays.

randomize([0.0, 1.1, 2.2, 3.3, 4.4, 5.5], percentage=50)
-> [0.0, -2.24, 4.31, 3.3, 4.4, 6.3]      

The problem is that I would like to do it with arrays of different dimensions using the same function. I have a clear idea for the random part but I can’t manage to select all the floats because of the different dimensions of my arrays.

I would really love a basic python or numpy solution, thanks!


You can remember the shape first, flatten array and then reshape it to the original shape.

import numpy as np

def randomize(ar, perc=50):
    # remember original shape
    sh = ar.shape
    # generate required number of random values
    rand_count = int(ar.size*perc/100)
    random_vals = np.random.rand(rand_count)
    # get random indices (without repetitions) to replace
    rand_ind = np.random.default_rng().choice(ar.size, size=rand_count, replace=False)

    # flatten the arary first
    flat_ar = ar.flatten()
    # replace required number of values by random values
    flat_ar[rand_ind] = random_vals
    # return in original shape
    return flat_ar.reshape(sh)