tags:

views:

134

answers:

2

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
+1  A: 

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.

Aaron Digulla
If x is your matrix then:scipy.sign(x)gives you the binary matrix.
speciousfool
+2  A: 

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.

bayer