简体   繁体   English

更改最接近Numpy数组中的值的n个元素的符号

[英]Changing the sign of the n elements closest to a value in a Numpy array

I wish to change the sign of the n elements in a numpy array that lies closest to a certain value, but not less. 我希望更改numpy数组中n个元素的符号,该数组最接近某个值,但不能更少。 That is, the elements must be equal or greater than the value. 也就是说,元素必须等于或大于该值。 Is there any fast Numpy methods that can do this efficiently with large arrays? 是否有任何快速的Numpy方法可以有效地使用大型数组?

The code that I have now takes n values that are higher or equal, but not closest, which is "okay", but not ideal for my results. 我现在的代码取n个值更高或相等但不是最接近的值,这是“好的”,但对我的结果并不理想。

def update(arr, n, value):
    updated = 0
    i = 0
    while updated < n:
        if arr[i] >= value: # just a random value above "value"
            arr[i] = -arr[i]
            updated +=1
        i += 1

arr = np.array([9, 8, 2, -4, 3, 4])
n = 3
value = 2
update(arr, n, value)

gives me 给我

arr = np.array([-9, -8, -2, -4, 3, 4])

when I instead want 当我反而想要的时候

arr = np.array([9, 8, -2, -4, -3, -4])

I'm not updating the array in place, but I'd do something like: 我没有更新阵列,但我会做类似的事情:

def update(arr, n, value):
    arr_copy = arr.copy()
    diffs = arr - value
    absolute_diffs = np.abs(diffs)
    update_indeces = np.argpartition(absolute_diffs, n)[:n]
    arr_copy[update_indeces] *= -1
    return arr_copy

You can use argpartition : 你可以使用argpartition

arr = np.random.random(20)
value = 0.5
n = 4

nl = np.count_nonzero(arr<value)
closest = np.argpartition(arr, (nl, nl+n-1))[nl:nl+n]
arr[closest] = -arr[closest]
arr
# array([ 0.33697627,  0.42607914, -0.63703314, -0.57517234,  0.82674228,
#        -0.52929285,  0.64776714,  0.25609886,  0.24681445,  0.2486823 ,
#         0.76740245,  0.02368603,  0.21498096, -0.51033841,  0.19901665,
#         0.30939207,  0.69036139,  0.83178506,  0.97243443,  0.47620492])

This should work: 这应该工作:

def flip_some(a, n, value):
    more_than = (a >= value)
    first_n_elements = (a < np.sort(a[more_than])[n])
    return np.where(more_than & first_n_elements, -a, a)

print(flip_some(np.array([9, 8, 2, -4, 3, 4]), 3, 2))
print(flip_some(np.arange(10), 2, 5))

Output: 输出:

[ 9 -8  -2 -4 -3 -4]
[ 0  1  2  3  4 -5 -6 -7  8  9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM