【发布时间】:2017-11-14 13:32:36
【问题描述】:
我有一个 numpy 数组 arr,我想用旧数组的 n 元素创建一个新数组,这些元素最接近给定数字 x。我在这里找到了一个有用的答案 (I have need the N minimum (index) values in a numpy array),但我的代码看起来很笨拙(我是 Python 的初学者):
def give_array_with_closest(x, n, arr):
newar = np.absolute(arr - (np.ones(len(arr)) * x)) #Subtract x from all array entries and take absolute value, so that the lowest entries are the ones closest to x
indexar = (newar).argsort()[:n] #get array with indices from n lowest entries of newar
result = np.empty(n)
for i in range(n):
result[i] = arr[indexar[i]]
return result
由于我对索引不感兴趣,而只对实际条目感兴趣,因此在这种情况下,其他问题的解决方案可能不是最好的。有没有更有效和更简单的方法来做到这一点?
【问题讨论】:
标签: python arrays python-2.7 numpy