我有两个 numpy 数组,我想丢弃两个列表中包含 nan 条目的所有条目。我该怎么做呢?(nan只能出现在第一个列表中)
我已经尝试过以下方法:
import numpy as np
a = np.array([1,2,np.nan,3,4])
b = np.array([5,6,7,8,9])
Run Code Online (Sandbox Code Playgroud)
如果我做:
b[np.where(np.isnan(a))]
Run Code Online (Sandbox Code Playgroud)
这返回给我:
np.array([7])
Run Code Online (Sandbox Code Playgroud)
不过,我想要
np.array([5,6,8,9])
Run Code Online (Sandbox Code Playgroud)
我尝试了几种不同的方法来使用 np.logic_not 和 ~ 来否定 np.where ,但我还没有设法让它工作。
你~之前需要否定np.isnan;np.where返回条件为 true 的索引,并且不容易否定索引,因为负索引在 python 中具有特殊含义(从序列末尾提取元素):
b[~np.isnan(a)]
# array([5, 6, 8, 9])
Run Code Online (Sandbox Code Playgroud)
以下也适用(尽管不是必需的):
b[np.where(~np.isnan(a))]
# array([5, 6, 8, 9])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6523 次 |
| 最近记录: |