2

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.

Conrad
  • 91
  • 2
  • 8
  • Does this answer your question? [Replacing Numpy elements if condition is met](https://stackoverflow.com/questions/19766757/replacing-numpy-elements-if-condition-is-met) – Zuku Mar 07 '20 at 14:06
  • Small in amplitude, right? Because e.g. -100 is smaller than 10**-2, but you don't want to set it to 0. – Andreas K. Mar 07 '20 at 15:17

2 Answers2

4

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

X[np.isclose(X, 0, atol=tolerance)] = 0
FBruzzesi
  • 6,385
  • 3
  • 15
  • 37
3

This should do the trick:

X[X < tolerance] = 0
Andreas K.
  • 9,282
  • 3
  • 40
  • 45
cn1adil
  • 56
  • 1