Purchawka
Purchawka

Reputation: 250

replacing values in a whole array

I would like to ask how I can change the values in a whole NumPy array.

For example I want to change every value which is < 1e-15 to be equal to 1e-15.

Upvotes: 2

Views: 413

Answers (4)

user707650
user707650

Reputation:

I like numpy.fmax (which was new to me), but for a possibly more generic case, I often use:

a[a < 1e-15] = 1e-15

(More generic in the sense that you can vary the condition, or that the replacement value is not equal to the comparison value.)

Upvotes: 2

Lauritz V. Thaulow
Lauritz V. Thaulow

Reputation: 51015

Assuming you mean a numpy array, and it's pointed to by a variable a:

np.fmax(a, 1e-15, a)

This finds the maximum of the two values given as the first two arguments (a and 1e-15) on a per-element basis, and writes the result back to the array given as the third argument, a.

I had a hard time finding the official docs for this function, but I found this.

Upvotes: 3

Sven Marnach
Sven Marnach

Reputation: 602605

Assuming you mean a lsit instead of an array, I'd recommend to use a list comprehension:

new_list = [max(x, 1e-15) for x in my_list]

(I also assume you mean 1e-15 == 10. ** (-15) instead of 10e-15 == 1e-14.)

There also exist "arrays" in Python: The class array.array from the standard library, and NumPy arrays.

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304463

If L is a list:

L[:] = [max(x, 10e-15) for x in L]

Upvotes: 3

Related Questions