![](/img/trans.png)
[英]Python/Pandas - Replacing an element in one dataframe with a value from another dataframe
[英]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.where
和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])
或者,對於就地修改:
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.