检查Python中numpy数组中的值是否在集合中

2024-05-14 10:17:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查NumPyArray中是否有一个集合中的值,如果有,则在数组中设置该区域=1。如果不设置keepRaster=2。

numpyArray = #some imported array
repeatSet= ([3, 5, 6, 8])

confusedRaster = numpyArray[numpy.where(numpyArray in repeatSet)]= 1

收益率:

<type 'exceptions.TypeError'>: unhashable type: 'numpy.ndarray'

有办法绕过它吗?

 for numpyArray
      if numpyArray in repeatSet
           confusedRaster = 1
      else
           keepRaster = 2

要澄清并寻求进一步帮助:

我现在要做的是把光栅输入放到一个数组中。我需要读取二维数组中的值并基于这些值创建另一个数组。如果数组值在集合中,则该值为1。如果它不在一个集合中,那么该值将从另一个输入派生出来,但我现在说的是77。这就是我现在使用的。我的测试输入大约有1500行和3500列。它总是在350排左右结冰。

for rowd in range(0, width):
    for cold in range (0, height):
        if numpyarray.item(rowd,cold) in repeatSet:
            confusedArray[rowd][cold] = 1
        else:
            if numpyarray.item(rowd,cold) == 0:
                confusedArray[rowd][cold] = 0
            else:
                confusedArray[rowd][cold] = 2

Tags: innumpyforiftyperange数组else
2条回答

以下是一种可能的方法:

numpyArray = np.array([1, 8, 35, 343, 23, 3, 8]) # could be n-Dimensional array
repeatSet = np.array([3, 5, 6, 8])
mask = (numpyArray[...,None] == repeatSet[None,...]).any(axis=-1) 
print mask
>>> [False  True False False False  True  True]

在1.4及更高版本中,numpy提供了^{}函数。

>>> test = np.array([0, 1, 2, 5, 0])
>>> states = [0, 2]
>>> np.in1d(test, states)
array([ True, False,  True, False,  True], dtype=bool)

你可以把它当作分配任务的遮罩。

>>> test[np.in1d(test, states)] = 1
>>> test
array([1, 1, 1, 5, 1])

下面是对numpy的索引和赋值语法的一些更复杂的使用,我认为它们将适用于您的问题。注意使用位运算符替换基于if的逻辑:

>>> numpy_array = numpy.arange(9).reshape((3, 3))
>>> confused_array = numpy.arange(9).reshape((3, 3)) % 2
>>> mask = numpy.in1d(numpy_array, repeat_set).reshape(numpy_array.shape)
>>> mask
array([[False, False, False],
       [ True, False,  True],
       [ True, False,  True]], dtype=bool)
>>> ~mask
array([[ True,  True,  True],
       [False,  True, False],
       [False,  True, False]], dtype=bool)
>>> numpy_array == 0
array([[ True, False, False],
       [False, False, False],
       [False, False, False]], dtype=bool)
>>> numpy_array != 0
array([[False,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
>>> confused_array[mask] = 1
>>> confused_array[~mask & (numpy_array == 0)] = 0
>>> confused_array[~mask & (numpy_array != 0)] = 2
>>> confused_array
array([[0, 2, 2],
       [1, 2, 1],
       [1, 2, 1]])

另一种方法是使用numpy.where,它创建一个全新的数组,使用mask为真的第二个参数的值,以及mask为假的第三个参数的值。(与赋值一样,参数可以是标量或与mask形状相同的数组。)这可能比上面的效率更高一些,而且肯定更简洁:

>>> numpy.where(mask, 1, numpy.where(numpy_array == 0, 0, 2))
array([[0, 2, 2],
       [1, 2, 1],
       [1, 2, 1]])

相关问题 更多 >

    热门问题