5
$\begingroup$

Imagine I have the following list

l = {{1,2,3},{4,10^(16),5}}

How do I efficiently replace the large number by a number (zero, for example). I can't seem to do it for a list of lists. Any ideas?

$\endgroup$
1
  • 4
    $\begingroup$ l /. _?(# > 1000 &) -> 0 ? $\endgroup$
    – MarcoB
    Jun 14, 2022 at 16:31

4 Answers 4

15
$\begingroup$

You could use 3-arg Clip:

Clip[l, {-Infinity, 10^10}, {0, 0}]

{{1, 2, 3}, {4, 0, 5}}

where I used 10^10 as the threshold.

$\endgroup$
5
$\begingroup$

Using Condition:

l /. x_Integer /; x > 10^6 -> 0
(*{{1, 2, 3}, {4, 0, 5}}*)

Or in the same way:

l /. x_?NumericQ /; x > 10^6 -> 0
(*{{1, 2, 3}, {4, 0, 5}}*)
$\endgroup$
3
$\begingroup$
l = {{1, 2, 3}, {4, 10^(16), 5}}

Define a high, low threshold as well as a substitute.

thlow = 2;
thhi = 3;
subst = 11;

Find positions of the entries that fall within the limits [2,3]:

pos = Position[l, x_ /; thlow <= x <= thhi, Infinity, Heads -> False]

{{1, 2}, {1, 3}}

To delete:

Delete[l, pos]

To replace with the substitute:

ReplacePart[l, Thread[pos -> subst]]

{{1, 11, 11}, {4, 10000000000000000, 5}}

$\endgroup$
2
$\begingroup$

I'm assuming you want something generalizable. Let's say your threshold is 10^10, then something like this:

Map[If[# > 10^10, 0, #] &, l, {2}]

You could also use ReplaceAll:

ReplaceAll[l, _?(GreaterThan[10^10]) -> 0]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.