I have a 2d array
a = array([[5, 0, 1, 0],
[0, 1, 3, 5],
[2, 3, 0, 0],
[4, 0, 2, 4],
[3, 2, 0, 3]])
and a 1d array
b = array([1, 2, 1, 2, 2])
which (b) tells how many non-zero elements we want to choose from each row of the array a.
For example, b[0] = 1 tells us that we have to choose 1 non-zero element from a[0], b[1] = 2 tells us that we have to choose 2 non-zero elements from a[1], and so on.
For a 1d array, it can be done using np.random.choice, but I can't find how to do it for a 2d array, so I have to use a for loop which slows the computation.
I want the result as 2d array as
array([[5, 0, 0, 0],
[0, 1, 0, 5],
[2, 0, 0, 0],
[0, 0, 2, 4],
[3, 2, 0, 0]])
Here, we have 1 element in row 1, 2 elements in row 2, 1 element in row 3 and so on as given in array b.
b?bare not random, it is the integer value of 80% of the number of non-zero elements in a for each row. Like forrow 1number of non-zero element is2,80% of 2is1.6,int(1.6)is1.