gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:24:53 25 4
gpt4 key购买 nike

我想检查 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

最佳答案

在 1.4 及更高版本中,numpy 提供了 in1d功能。

>>> 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]])

关于python - 检查集合中的值是否在python中的numpy数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10690233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com