查找numpy数组中最近的四分之一?

klr1opcd  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(127)

我有一个numpy数组,其中包含0.25步长的数字。所以这个数组的一部分是[-38.25,-38,-37.75,-37.5]。我希望能够找到最接近的和最低的四分之一到任何数字。
例如,如果输入为-37.778,则最接近的四分之一将为-37.75和-38,最低的将为-38。所以输出应该是-38,或者更好的是对应的索引为-38。
我用近似值手动做,后来用np.searchsorted,但我认为一定有更好的方法。另外,数组有400个元素,所以我不确定这样做是否最好。

7uzetpgm

7uzetpgm1#

从描述中可以计算指数。乘以8并转换为整数以获得索引 * 2。如果最接近的是向下舍入,则这将是偶数,如果最接近的是向上舍入,则这将是奇数。

import numpy as np

threshold = np.arange( -38., -34.9, 0.25 )
threshold
# array([-38.  , -37.75, -37.5 , -37.25, -37.  , -36.75, -36.5 , -36.25,
#        -36.  , -35.75, -35.5 , -35.25, -35.  ])

np.random.seed( 123 )
arr = (np.random.rand( 10 )*3-38.).round(2) # Some values to try. 
# Rounded to print arr on a line.

index_x2 = np.floor(( ( arr-threshold.min() ) * 8 )).astype( np.int64 )
# index * 2 = (arr-lowest threshold ) * 8 as an integer

floor_index = index_x2 // 2   # The threshold index always rounded down.  

nearest_index = ( index_x2 + 1 ) // 2  # The threshold index rounded to nearest.

print( arr )                                  
# [-35.91 -37.14 -37.32 -36.35 -35.84 -36.73 -35.06 -35.95 -36.56 -36.82 ]

print( floor_index )
# [ 8  3  2  6  8  5 11  8  5  4]

print( nearest_index )
# [ 8  3  3  7  9  5 12  8  6  5]

print( threshold[ floor_index ] )
# [-36.   -37.25 -37.5  -36.5  -36.   -36.75 -35.25 -36.   -36.75 -37.  ]

print( threshold[ nearest_index ])
# [-36.   -37.25 -37.25 -36.25 -35.75 -36.75 -35.   -36.   -36.5  -36.75]

相关问题