I have a large numpy matrix of the order of 10,000 rows and 10,000 columns of float type. For each row, I need to find the column index with maximum value and select each column at most once.
For example, for the given array arr, I need the output as a list/array of (row index, column index) tuples as given in out:
arr = np.array(
[[0.86, 0.23, 0.83, 0.79],
[0.15, 0.98, 0.86, 0.47],
[1. , 0.08, 0.01, 0.04],
[0.78, 0.82, 0.17, 0.56],
[0.73, 0.91, 0.52, 0.31]])
out = [(0,0),(1,1),(2,3),(3,2)]
Explanation:
- Initially
outis empty. - For
row 0, the maximum value is0.86incolumn 0, sooutis now[(0,0)] - For
row 1, the maximum value is0.98incolumn 1, andcolumn 1isn't already present in out, sooutis now[(0,0),(1,1)] - For
row 2, the maximum value is1incolumn 0, butcolumn 0has already been selected, so we look for next maximum, i.e.0.08incolumn 1, which is also present inout, then next maximum, i.e.0.04incolumn 3, sooutis now[(0,0),(1,1),(2,3)] - Similarly, for
row 3, the column with maximum value that hasn't been already selected iscolumn 2, so finaloutis[(0,0),(1,1),(2,3),(3,2)]
I want to compute it as efficiently as possible. The O(n2) solution using 2 for loops is trivial, so any solution better than this (either better time complexity or better runtime using inbuilt numpy functions) would be very helpful.