Convert a decimal matrix to a binary matrix in SciPy
Question
Suppose I have a integer matrix which represents who has emailed whom and how many times. For social network analysis I'd like to make a simple undirected graph. So I need to convert the matrix to binary matrix and later into a list of tuples.
My question: is there a fast, convenient way to reduce the decimal matrix to a binary matrix.
Such that:
26, 3, 0
3, 195, 1
0, 1, 17
Becomes:
1, 1, 0
1, 1, 1
0, 1, 1
Solution
Apply the scipy.sign
function to every cell in the matrix.
[EDIT] Cudos to speciousfool:
If x
is your matrix then scipy.sign(x)
gives you the binary matrix.
OTHER TIPS
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 a != 0
part. You can apply boolean expressions to arrays and it will return an array of booleans. Then it is converted to ints.
You can also try this:
>>>x,y = scipy.where(yourMatrix>0)
>>>yourMatrix[:,:] = 0
>>>yourMatrix[x,y] = 1
i guess this will also be faster.