How Do I convert an int array of 0s and 1s into Boolean in numpy?

let’s say I have this:

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

I would like to convert a into boolean, how do I do this?

a.astype(bool) dosn’t work since it is a multidimensional array and it needs to be done without a for loop

Hey!
I am not the very best at using maps, but I think that is what you might be seeking here:

I think it only works on lists that are always the same dimensions (in other words, I’m not sure if you can make a general mapping function for arrays that are sometimes one-dimensional, other times four-dimensional).

I hope it makes sense and helps you :slight_smile:

1 Like
a = np.array([[0,0,1,0,0],[1,0,0,1,0], [1,0,1,0,0]])
a.astype(np.bool)
# output:
array([[False, False,  True, False, False],
       [ True, False, False,  True, False],
       [ True, False,  True, False, False]])

Looks to me as though it worked perfectly.
It’s a wild guess, but I guess because np.array only has one dedicated data-type for all it’s entrys - you don’t need to loop.

Like, Python arrays have a datatype for every single entry. That’s why you can mix everything in them.
np.arrays in part are super efficient, because they have basic values in each cell and only one-datatype entry that is applied to read out the values. So in return, changing that type via .astype() will automatically apply to all entries.
But again - that’s just my guess.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.