Python Forum

Full Version: Numpy, array(2d,bool), flipping regions.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I got a numpy 2d bool array. And like to flip(True/False) some array regions. But have not found any hints in numpy docs.

So ... Is there some numpy-way to flip the values in a given region inside an numpy-array ?

			## ... ... ...

			[maxR, maxC] = tmp_nArray.shape
			[maxR, maxC] = [maxR-1, maxC-1]

			if(0): ## set corners -- not working due to turdsize > 1.
				tmp_nArray[0, 0] = True
				tmp_nArray[0, maxC] = True
				tmp_nArray[maxR, 0] = True
				tmp_nArray[maxR, maxC] = True

			if(0): ## try turning all borders to white/true. -- nope, now other corners go wrong.
				tmp_nArray[0, 0:maxC] = True
				tmp_nArray[maxR, 0:maxC] = True
				tmp_nArray[0:maxR, 0] = True
				tmp_nArray[0:maxR, maxC] = True

			if(1): ## try flipping values for the borders. (do corners only ones)
				# ???

			## ... ... ...
You could try this perhaps (not sure it is the best solution)
>>> a = np.array([0,1,1,0,0,1,0,1,0,1,1,1], dtype=bool)
>>> a
array([False,  True,  True, False, False,  True, False,  True, False,
        True,  True,  True])
>>> a[3:7] ^= np.ones(a[3:7].shape, dtype=bool)
>>> a
array([False,  True,  True,  True,  True, False,  True,  True, False,
        True,  True,  True])
>>> 
Or this
>>> import numpy as np
>>> a = np.array([0,1,1,0,0,1,0,1,0,1,1,1], dtype=bool)
>>> a
array([False,  True,  True, False, False,  True, False,  True, False,
        True,  True,  True])
>>> a[3:7] = np.logical_not(a[3:7])
>>> a
array([False,  True,  True,  True,  True, False,  True,  True, False,
        True,  True,  True])
Aha, that simplifies things. Thanks
def npArray_test3():

	def create_mask(shape):
		_r_,_c_ = range(2)
		(rmax, cmax) = shape
		m = np.ones(shape, dtype=bool)
		m[1:rmax-1, 1:cmax-1] = np.zeros(m[1:rmax-1, 1:cmax-1].shape, dtype=bool)
		return m

	a = np.arange(4*5).reshape(4, 5)
	print(a)

	m = create_mask(a.shape)
	print(m)

	np.putmask(a, m, -(a+1))
	print(a)
Output:
[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] [[ True True True True True] [ True False False False True] [ True False False False True] [ True True True True True]] [[ -1 -2 -3 -4 -5] [ -6 6 7 8 -10] [-11 11 12 13 -15] [-16 -17 -18 -19 -20]]