简体   繁体   中英

Converting predefined 2d Array into 2d bool array

I am given a predefined array

a = [[2 3 4]
     [5 6 7]
     [8 9 10]]

my issue is converting this array into a boolean array where all even numbers are true. Any help is appreciated!

I would use numpy, and it's pretty straightforward:

import numpy as np

a = [[2, 3, 4],
     [5, 6, 7],
     [8, 9, 10]]
a = np.asarray(a)
(a % 2) == 0

Do as follows using Numpy:

 import numpy as np a = [[2, 3, 4], [5, 6, 7], [8, 9, 10]] aBool=(np.asarray(a)%2==0)

The variable aBool will contain True where there is an Even value and False for an Odd value.

 array([[ True, False, True], [False, True, False], [ True, False, True]])

This is adapted from the answer found here :

a=np.array([1,2,3,4,5,6])

answer = (a[a%2==0])
print(answer)

which is essentially what Andrew said but without using NumPy

If you're interested in getting booleans and testing for certain conditions within a NumPy array you can find a neat post here

This can be done simply using one line (if you don't want to use numpy):

[[i % 2 == 0 for i in sublist] for sublist in a]

>>> [[True, False, True], [False, True, False], [True, False, True]]

Here, i % 2 denotes the modulus operator, which gives the remainder when the first number is divided by the second. In this case, for even numbers i % 2 = 0 , and for odd numbers i % 2 = 1 . The two = signs means that the expression is evaluated as a boolean.

The two for loops iterate over each list inside of the 2D list.

This can be extended if you find this format easier to understand, but it essentially does the same thing:

>>> newlist = []
>>> for sublist in a:
        partial_list = []
        for i in sublist:
                partial_list.append(i % 2 == 0)
        newlist.append(partial_list)


>>> newlist
[[True, False, True], [False, True, False], [True, False, True]]

Why not to mention negations:

a = [[2, 3, 4],
     [5, 6, 7],
     [8, 9, 10]]

>>> ~np.array(a)%2
array([[1, 0, 1],
       [0, 1, 0],
       [1, 0, 1]], dtype=int32)

This is a boolean form:

>>> ~(np.array(a)%2).astype(bool)
array([[ True, False,  True],
       [False,  True, False],
       [ True, False,  True]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM