I have a matrix
A = np.zeros((n,n))
with say n=4. I have another matrix
B = np.array(
[7, 3, 5, 4],
[4, 3, 2, 1],
[6, 7, 4, 5],
[1, 2, 3, 4]
)
First I need the indices of the smallest k elements (e.g. 2) in every row of B
, in this case it would be
np.array(
[1, 3],
[3, 2],
[2, 3],
[0, 1]
)
I can do this doing np.argsort
but that ends up sorting the whole array, np.argpartition
can sort the first k elements but I need a way to get the indices. Lastly I want to insert the smallest k values of B
into A
at the indices giving the matrix
A = np.array(
[0, 3, 0, 4],
[0, 0, 2, 1],
[0, 0, 4, 5],
[1, 2, 0, 0]
)
What's a possible way to this?