Home > Net >  Find the index of every instance of n in ndarray using numpy
Find the index of every instance of n in ndarray using numpy

Time:07-01

I have an 2d array, and I'd like to invert 0 to 1 and vice versa, but only on the first row.

I have an example below on how to do it, but it affects the entire ndarray.

np.where((a==0)|(a==1), a^1, a)
For example:

a = np.array([[0,1,0,1], [1,0,0,1]])
print(a)
array([[0, 1, 0, 1],
       [1, 0, 0, 1]])

np.where((a==0)|(a==1), a^1, a)

Input:

array([[0, 1, 0, 1],
       [1, 0, 0, 1]])

Current output:

array([[1, 0, 1, 0],
       [0, 1, 1, 0]])

Desired output:

array([[1, 0, 1, 0],
       [1, 0, 0, 1]])

Thanks.

CodePudding user response:

Simply Use:

In [1753]: a[0] = 1 - a[0]

In [1754]: a
Out[1754]: 
array([[1, 0, 1, 0],
       [1, 0, 0, 1]])

OR

In [1738]: a[0] = np.where((a==0)|(a==1), a^1, a)[0]

In [1739]: a
Out[1739]: 
array([[1, 0, 1, 0],
       [1, 0, 0, 1]])

OR use np.logical_not:

In [1744]: a[0] = np.logical_not(a[0]).astype(int)

In [1745]: a
Out[1745]: 
array([[1, 0, 1, 0],
       [1, 0, 0, 1]])

CodePudding user response:

It is recommended to use indexing by NumPy if possible, not other modules like np.where:

mask_0 = a[0] == 0
# [ True False  True False]

mask_1 = a[0] == 1
# [False  True False  True]

a[0, mask_0] = 1
# [[1 1 1 1]
#  [1 0 0 1]]

a[0, mask_1] = 0
# [[1 0 1 0]
#  [1 0 0 1]]

if you have just 0 and 1 in the array (besides the porwal asnwer that is very easy to use i.e. a[0] = 1 - a[0]) you can convert to Boolean array based on that as:

bool_a = a[0].astype(bool)
# [False  True False  True]

res = ~bool_a                 # inverted
# [ True False  True False]

res.astype(int)
# [1 0 1 0]

a[0] = res.astype(int)
# [[1 0 1 0]
#  [1 0 0 1]]

that can be written in one line as:

a[0] = (~a[0].astype(bool)).astype(int)
  • Related