[SciPy-User] From 1-D boolean array to integer index

josef.pktd@gmai... josef.pktd@gmai...
Tue Oct 11 12:38:28 CDT 2011


On Tue, Oct 11, 2011 at 1:29 PM, Jacob Biesinger
<jake.biesinger@gmail.com> wrote:
> Hi all!
> This seems a trivial question, but I couldn't find it in the archives.  I
> have a 1-D bool array which I'd like to convert to an integer index.  The
> best I've come up with is:
>>>> int(''.join(['1' if e else '0' for e in sp.array([True, False])]), 2)
> 2
>>>> int(''.join(['1' if e else '0' for e in sp.array([True, False, True])]),
>>>> 2)
> 5
> Is there an easier way to do this?

I don't quite understand what you'd like to do, but there is

>>> np.nonzero(np.array([True, False, True]))
(array([0, 2]),)

>>> np.array([True, False, True]).astype(int)
array([1, 0, 1])
>>> np.array([True, False, True]).astype('S1')
array(['T', 'F', 'T'],
      dtype='|S1')
>>> np.array([True, False, True]).astype(int).astype('S1')
array(['1', '0', '1'],
      dtype='|S1')

Josef

> Thanks!
> --
> Jake Biesinger
> Graduate Student
> Xie Lab, UC Irvine
>
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
>


More information about the SciPy-User mailing list