How to set very small numbers to zero in numpy arrays?

Viewed 2663

What is the best way to set numbers smaller than a specified tolerance to zero in a real numpy array? In particular, my array has 3 dimensions.

import numpy as np

N = 25
D = 50
tolerance = 10**-2

X = np.random.normal(0, 1, (N, D, 4))

I would like to set to 0 all values of X smaller than the tolerance set.

2 Answers

I think a better way would be to use np.isclose

X[np.isclose(X, 0, atol=tolerance)] = 0

This should do the trick:

X[X < tolerance] = 0
Related