I'm looking for the quickest way to do the following:
arr = np.array([2.,0.5,1.3,4.5,7.4])
I want to build a new array (or overwrite current) where I put to zero everything except the n highest entries.
[2.0,0,0,4.5,7.4]
I'm looking for the quickest way to do the following:
arr = np.array([2.,0.5,1.3,4.5,7.4])
I want to build a new array (or overwrite current) where I put to zero everything except the n highest entries.
[2.0,0,0,4.5,7.4]
I am not sure whether it is the fastest or not but it gives the expected output
import numpy as np
array = np.array([2.,0.5,1.3,4.5,7.4])
l = len(array)
order = array.argsort()
ranks = order.argsort()
n = 3
array = [array[i] if ranks[i] >= l - n else 0 for i in range(len(ranks))]
print(array)
Let's define the array and a value for N, so we keep the N highest elements.
N = 3
arr = np.array([2.,0.5,1.3,4.5,7.4])
Using argsort we can retrieve the order of elements from lower to highest. We just need to subtract from the size of the array to get from highest to lower.
order = arr.argsort()
order = arr.size - order
Then replace with zeros the smaller elements:
arr[order > N] = 0