簡體   English   中英

將 Python 中的一個元素替換為另一個元素

[英]Replacing one element with another in Python

我想用矩陣P中的0替換inf 隨附所需的 output。

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

所需的 output 是:

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

您可以組合numpy.wherenumpy.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])

或者,對於就地修改:

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

作為替代方法,如果確定我們只有inf s(不是nan s),還有另一個 NumPy 工具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]

這是直截了當的(完全適用於np.inf s)並且不需要使用logical not ~

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM