Converting decimal matrix to binary matrix in SciPy

Suppose I have an integer matrix that represents who has emailed who, and how many times. For social network analysis, I would like to make a simple undirected graph. So I need to convert the matrix to a binary matrix and then to a list of tuples.

My question is, is there a quick, convenient way to reduce a decimal matrix to a binary matrix.

Thus:

26, 3, 0
3, 195, 1
0, 1, 17

      

becomes:

1, 1, 0
1, 1, 1
0, 1, 1

      

+2


source to share


3 answers


Apply the function scipy.sign

to each cell in the matrix.

[EDIT] Claims to speciousfool :



If x

is your matrix then scipy.sign(x)

gives you a binary matrix.

+2


source


You can do the following:

>>> import scipy
>>> a = scipy.array((12, 0, -1, 23, 0))
array([12,  0, -1, 23,  0])
>>> (a != 0).astype(int)
array([1, 0, 1, 1, 0])

      



The magic is in the part a != 0

. You can apply boolean expressions to arrays and it will return an array of boolean expressions. It is then converted to ints.

+2


source


You can also try this:

>>>x,y = scipy.where(yourMatrix>0)
>>>yourMatrix[:,:] = 0
>>>yourMatrix[x,y] = 1

      

I think it will be faster.

+1


source







All Articles