Home > Net >  Replacing one element with another in Python
Replacing one element with another in Python

Time:05-09

I would like to replace inf with 0 in the matrix, P. The desired output is attached.

import numpy as np
P = np.array([-1.54511316e 12,            -inf, -1.54511316e 12,            -inf,
                  -inf,            -inf,            -inf])

The desired output is

array([-1.54511316e 12,            0, -1.54511316e 12,            0,
                  0,            0,            0])

CodePudding user response:

You can combine numpy.where and numpy.isfinite:

P2 = np.where(np.isfinite(P), P, 0)

output:

array([-1.54511316e 12,  0.00000000e 00, -1.54511316e 12,  0.00000000e 00,
        0.00000000e 00,  0.00000000e 00,  0.00000000e 00])

Or, for in place modification:

P[~np.isfinite(P)] = 0
  • Related