在 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
为 true,并且来自第三个参数的值,其中mask
是假的。 (与赋值一样,参数可以是标量或形状与mask
.) 这可能比上面的更有效,而且肯定更简洁:
>>> numpy.where(mask, 1, numpy.where(numpy_array == 0, 0, 2))
array([[0, 2, 2],
[1, 2, 1],
[1, 2, 1]])