简体   繁体   中英

python - numpy - get index of matrix that contains True

In the following code

import numpy as np

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

I want to get retrieve the array [True, False, True, False] corresponding to the lists that contain at least one True.

Try this:

You can use np.any which test whether any array element along a given axis evaluates to True .

result = np.any(arr, axis=1)

OR,

You can use np.sum to sum all the values along the column axis and compare these values if they are greater than or equal to 1 which returns a boolean mask.

result = (np.sum(arr, axis=1) >= 1)

Result:

[True False  True False]

As suggested in the comments, the best way to accomplish that is to use np.any which tests whether any element along a given axis evaluates to True. In practice:

import numpy as np

a = np.array([
           [False,  True, False],
           [False, False, False],
           [False, False,  True],
           [False, False, False]])

np.any(a, axis=1)
array([ True, False,  True, False])

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