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])
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
As an alternative way, if being sure that we have only inf
s (not nan
s), there is another NumPy tool np.isinf
:
P[np.isinf(P)] = 0
# [-1.54511316e+12 0.00000000e+00 -1.54511316e+12 0.00000000e+00
# 0.00000000e+00 0.00000000e+00 0.00000000e+00]
which is straight forward (exactly for np.inf
s) and don't need to use logical not ~
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.