映射数组值的有效方法

Efficient way for mapping array values

我有 numpy 数组,我确实想将数组值的范围映射到特定值:

import numpy as np

array = [
[328, 124, 146, 117, 147, 109, 139, 100, 140, 98, 128, 101, 121, 95, 111, 89, 114, 82, 106, 77, 97, 71, 273], 
[132, 121, 121, 117, 114, 110, 99, 163, 89, 81, 83, 81, 91, 91, 89, 144, 89, 81, 81, 75, 69, 68, 68], 
[164, 114, 117, 110, 105, 105, 97, 91, 142, 80, 131, 77, 122, 81, 108, 74, 77, 75, 69, 71, 68, 63, 87], 
[121, 116, 110, 103, 104, 99, 90, 84, 77, 137, 77, 125, 99, 128, 79, 73, 69, 71, 68, 70, 60, 53, 64], 
[151, 100, 103, 99, 379, 88, 264, 78, 135, 77, 121, 97, 113, 75, 100, 62, 232, 65, 350, 54, 56, 50, 75], 
[101, 93, 121, 90, 84, 92, 86, 78, 74, 113, 66, 115, 72, 100, 63, 67, 60, 57, 57, 47, 47, 44, 43], 
[146, 89, 116, 86, 87, 85, 79, 73, 101, 59, 98, 63, 107, 64, 62, 56, 56, 52, 48, 50, 46, 38, 68], 
[89, 113, 108, 83, 82, 78, 74, 125, 69, 67, 57, 65, 67, 56, 58, 105, 49, 52, 69, 59, 63, 34, 43], 
[127, 87, 78, 79, 105, 74, 163, 64, 61, 61, 56, 235, 61, 48, 51, 43, 134, 40, 63, 28, 31, 26, 55], 
[76, 79, 75, 70, 72, 69, 62, 58, 53, 52, 49, 50, 53, 43, 39, 37, 41, 36, 31, 29, 26, 18, 17], 
[274, 73, 96, 71, 92, 64, 87, 57, 82, 53, 81, 30, 73, 41, 66, 37, 52, 31, 49, 22, 50, 15, 211]]

array = np.array(array)

def mapVal(val, table = [140, 195, 250, 350, 450]):
    """
    Function: mapVal, to quantify depth values manually.
    ---
    Parameters:
    @param: val, nd-array.
    @param: table, list, mapping table.

    ---
    @return: None.
    """
    
    val[val <= table[0]]  = 0
    val[val >  table[0] & val <=  table[1]]  = 1
    val[val >  table[1] & val <=  table[2]]  = 2
    val[val >  table[2] & val <=  table[3]]  = 3
    val[val >  table[3] & val <=  table[4]]  = 4
    val[val >  table[4]]  = 5

但是我收到了这个错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我知道我可以使用低效的循环,但我想问一下是否有更好的解决方案,在此先感谢。

如评论中所述,首先通过在条件检查周围使用括号来解决 ValueError,以避免首先评估 bit-wise 和运算符 &,这是默认设置行为。

例如:

val[(val > table[0]) & (val <= table[1])]

接下来,为了您搜索更高效的方法,您可以使用built-in np.digitize 功能来帮助您完成您正在做的事情:

np.digitize(array, table)

有一种更简单、更快速的方法来做你想做的事:

table = np.array([140, 195, 250, 350, 450])
result = np.searchsorted(table, array)

这假设 table 是 排序的 ,尽管这里就是这种情况。如果不是,则可以使用 np.argsort 重新排序 table 并使用 np.digitize 重新映射值。