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 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 Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.