Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipperemy/56a2e3eb6b1d719528597c5d2c984eb3 to your computer and use it in GitHub Desktop.
Save philipperemy/56a2e3eb6b1d719528597c5d2c984eb3 to your computer and use it in GitHub Desktop.
import numpy as np
# FIND LARGEST K ELEMENTS IN A 2D ARRAY IN NUMPY
def find_k_largest_elements_in_2d_array(arr: np.array, k=1):
assert len(arr.shape) == 2
h, w = arr.shape
top_indices = np.flip(arr.flatten().argsort()[-k:])
return np.divmod(top_indices, w)
def test():
arr = np.random.uniform(size=(1000, 1000))
k = 10
top_k = find_k_largest_elements_in_2d_array(arr, k=k)
for i in range(k):
assert np.sum(arr[top_k][i] <= arr) == i + 1
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment