How to convert numpy matrix with different floats to matrix with zeros and ones

Given a numpy matrix (mixed_float_matrix) with a variety of float values, how do you convert it into a matrix, with zeros and ones (ones in place of non-zero values in the original matrix)?

This is how:

m = (mixed_float_matrix > 0).astype(int)

You can test it like with the following:

import numpy as np
 
# create a "random" matrix
a=np.zeros(100)
p=np.random.permutation(100)
a[p[:10]]=127
a[p[10:20]]=42
a.reshape(10,10)
# a is now a random matrix with values 0, 42 an 127 in different places
 
a = (a > 0).astype(int)
# a is now a matrix with ones and zeros

Leave a Reply