Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a numpy boolean array to int one with distinct values

Tags:

python

numpy

I've read through most of How to convert a boolean array to an int array , but I was still at loss with, how to (most efficiently) convert a numpy bool array to an int array, but with distinct values. For instance, I have:

>>> k=np.array([True, False, False, True, False])
>>> print k
[ True False False  True False]

I'd like this to be converted to an array, where True is say, 2, and False is say 5.

Of course, I can always set up a linear equation:

>>> print 5-k*3
[2 5 5 2 5]

... which, while vectorized, needlessly employs both addition (subtraction) and multiplication; furthermore, if I'd want the opposite values (5 for True and 2 for False), I basically have to use (and recalculate) a different equation:

>>> print 2+k*3
[5 2 2 5 2]

... which is a bit of a readability issue for me.

In essence, this is merely a selection/mapping operation - but one which I'd like done in the numpy domain. How could I do that?

like image 669
sdaau Avatar asked Dec 25 '22 16:12

sdaau


2 Answers

Seems like numpy.where is exactly what you want:

>>> import numpy as np
>>> k = np.array([True, False, False, True, False])
>>> np.where(k, 2, 5)
array([2, 5, 5, 2, 5])
like image 59
mgilson Avatar answered Dec 28 '22 13:12

mgilson


Well, it seems I have to make a np.array (not a Python list!) containing the two distinct values:

>>> z=np.array([2,5])
>>> print z
[2 5]

... and then I can simply cast the boolean array (k) to int, and use that as selection indices in the "distinct values array" (z):

>>> print z[k.astype(int)]
[5 2 2 5 2]

It is also trivial to change the [2,5] to [5,2], so that is good.

I'm just not sure if this is the right way to do it (that is, maybe there exists something like (pseudocode) k.asdistinctvalues([2,5]) or something like that?)

like image 32
sdaau Avatar answered Dec 28 '22 15:12

sdaau