Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.array boolean to binary?

Tags:

python

numpy

I am trying to rewrite a matlab code in python27. There is a matlab line as follows:

vector_C = vector_A > vector_B;

If I try to write this in python using numpy it will be the same, but the result will be an array of booleans instead of binaries. I want the result to be in binaries. Is there a way to make it return binary or should I convert manually each time? Is there a quick way of converting it? I am new to python. Thanks.

like image 633
delete_this_account Avatar asked May 10 '12 00:05

delete_this_account


People also ask

How do you convert a boolean array to an int array in Python?

To convert a Boolean array a to an integer array, use the a. astype(int) method call. The single argument int specifies the desired data type of each array item. NumPy converts on a best-effort basis.

How do you flip a boolean array?

We can also use the Tilde operator (~) also known as bitwise negation operator in computing to invert the given array. It takes the number n as binary number and “flips” all 0 bits to 1 and 1 to 0 to obtain the complement binary number.

How do you create a boolean array in NumPy?

A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.

How do I invert NumPy?

invert() function is used to Compute the bit-wise Inversion of an array element-wise. It computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. For signed integer inputs, the two's complement is returned.


2 Answers

Even though vector_C may have dtype=bool, you can still do operations such as the following:

In [1]: vector_A = scipy.randn(4)

In [2]: vector_B = scipy.zeros(4)

In [3]: vector_A
Out[3]: array([ 0.12515902, -0.53244222, -0.67717936, -0.74164708])

In [4]: vector_B
Out[4]: array([ 0.,  0.,  0.,  0.])

In [5]: vector_C = vector_A > vector_B

In [6]: vector_C
Out[6]: array([ True, False, False, False], dtype=bool)

In [7]: vector_C.sum()
Out[7]: 1

In [8]: vector_C.mean()
Out[8]: 0.25

In [9]: 3 - vector_C
Out[9]: array([2, 3, 3, 3])

So, in short, you probably don't have to do anything extra.

But if you must do a conversion, you may use astype:

In [10]: vector_C.astype(int)
Out[10]: array([1, 0, 0, 0])

In [11]: vector_C.astype(float)
Out[11]: array([ 1.,  0.,  0.,  0.])
like image 73
Steve Tjoa Avatar answered Sep 30 '22 07:09

Steve Tjoa


You can force numpy to store the elements as integers. It treats 0 as false and 1 as true.

import numpy

vector_C = numpy.array( vector_A > vector_B, dtype=int) ;
like image 37
Rob Falck Avatar answered Sep 30 '22 09:09

Rob Falck