Good morning to everyone,

I am trying to generate a 4D numpy array that contains a random number of “nan”. I am following a methodology that I have found in this page (How to randomly insert NaN in a matrix with NumPy in Python ? - GeeksforGeeks), concretely “method 2”, that consists in creating a mask. This method, however, considers a 2D numpy array - a matrix-, but in my case I am dealing with a 4D numpy array.

Let me show you an example of my problem.

Array “mask” is a 4D boolean array full of “False”:

mask = [ [ [ [F F F F], [F F F F] ], [ [F F F F], [F F F F] ] ],

[ [F F F F], [F F F F] ], [ [F F F F], [F F F F] ] ] ]

Array “random_nan” is a 4D array that contains randomly generated integer numbers that represent the number of elements for each sub-array of “mas” that will be turned to “True” (T):

random_nan = [ [ [ [2], [3] ], [ [1], [2] ] ], [ [ [0], [2] ], [ [1], [3] ] ] ]

So, what I want to get is a “result” array like this:

result = [ [ [ [T T F F], [T T T F] ], [ [T F F F], [T T F F] ] ],

[ [F F F F], [T T F F] ], [ [T F F F], [T T T F] ] ] ]

I am struggling, but I can’t think of a “pythonic” way to get this “result” without having to set “for” loops to explicitly run for the different sub-arrays.

I would be glad if you could give me a hand with this problem.

Thanks in advance.

Joan