gpt4 book ai didi

python - 删除 numpy 数组中的 NaN

转载 作者:太空狗 更新时间:2023-10-30 00:24:12 26 4
gpt4 key购买 nike

我有两个包含 NaN 的 numpy 数组:

A = np.array([np.nan,   2,   np.nan,   3,   4])
B = np.array([ 1 , 2, 3 , 4, np.nan])

是否有任何聪明的方法使用 numpy 删除两个数组中的 NaN,并删除另一个列表中相应索引上的内容?让它看起来像这样:

A = array([  2,   3, ])
B = array([ 2, 4, ])

最佳答案

你可以做的是将 2 个数组加在一起,这将用 NaN 值覆盖它们没有的地方,然后使用它来生成 bool 掩码索引,然后使用索引索引到你的原始 numpy 数组中:

In [193]:

A = np.array([np.nan, 2, np.nan, 3, 4])
B = np.array([ 1 , 2, 3 , 4, np.nan])
idx = np.where(~np.isnan(A+B))
idx
print(A[idx])
print(B[idx])
[ 2. 3.]
[ 2. 4.]

A+B 的输出:

In [194]:

A+B
Out[194]:
array([ nan, 4., nan, 7., nan])

编辑

正如@Oliver W. 正确指出的那样,np.where 是不必要的,因为 np.isnan 将生成一个 bool 索引,您可以使用该索引索引到数组:

In [199]:

A = np.array([np.nan, 2, np.nan, 3, 4])
B = np.array([ 1 , 2, 3 , 4, np.nan])
idx = (~np.isnan(A+B))
print(A[idx])
print(B[idx])
[ 2. 3.]
[ 2. 4.]

关于python - 删除 numpy 数组中的 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29120626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com