Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary numpy array to list of integers?

I have a binary array, and I would like to convert it into a list of integers, where each int is a row of the array.

For example:

from numpy import *
a = array([[1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 1, 1, 1]])

I would like to convert a to [12, 4, 7, 15].

like image 467
Eli Sander Avatar asked Mar 19 '13 16:03

Eli Sander


2 Answers

@SteveTjoa's answer is fine, but for kicks, here's a numpy one-liner:

In [19]: a
Out[19]: 
array([[1, 1, 0, 0],
       [0, 1, 0, 0],
       [0, 1, 1, 1],
       [1, 1, 1, 1]])

In [20]: a.dot(1 << arange(a.shape[-1] - 1, -1, -1))
Out[20]: array([12,  4,  7, 15])

(arange is numpy.arange.)

If the bits are in the opposite order, change the order of the values produced by arange:

In [25]: a.dot(1 << arange(a.shape[-1]))
Out[25]: array([ 3,  2, 14, 15])
like image 90
Warren Weckesser Avatar answered Oct 12 '22 21:10

Warren Weckesser


I once asked a similar question here. Here was my answer, adapted for your question:

def bool2int(x):
    y = 0
    for i,j in enumerate(x):
        y += j<<i
    return y

In [20]: a
Out[20]: 
array([[1, 1, 0, 0],
       [0, 1, 0, 0],
       [0, 1, 1, 1],
       [1, 1, 1, 1]])

In [21]: [bool2int(x[::-1]) for x in a]
Out[21]: [12, 4, 7, 15]
like image 42
Steve Tjoa Avatar answered Oct 12 '22 21:10

Steve Tjoa