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

Daniel Casasampera :

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.

cn1adil :

This should do the trick:

X[X < tolerance] = 0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33217&siteId=1