【问题标题】:Remove elements from lists when index is one lists is NaN当索引为一时从列表中删除元素列表为 NaN
【发布时间】:2017-04-28 06:59:41
【问题描述】:

假设我有三个列表,其中一个包含 NaN(我认为它们是“NaN”,它们从先前的掩码数组操作中打印为“--”):

a = [1,2,3,4,5]
b = [6,7,--,9,--]
c = [6,7,8,9,10]

我想执行一个遍历 b 的操作,并从 b[i]=NaN 所在的所有列表中删除索引。我在想这样的事情:

for i in range(0,len(b):
    if b[i] = NaN:
        del.a[i] etc

b 是在我的代码前面的某些条件下通过屏蔽 c 生成的,如下所示:

b = np.ma.MaskedArray(c, condition)

谢谢!

【问题讨论】:

标签: python arrays list nan


【解决方案1】:

使用 numpy 很容易做到这一点:

import numpy as np
a = np.array([1,2,3,4,5])
b = np.array([6,7,np.NaN,9,np.NaN])
c = np.array([6,7,8,9,10])

where_are_nans = np.isnan(b)
filtered_array = a[~where_are_nans] #note the ~ negation
print(filtered_array)

你可以很容易地看到它返回:

[1 2 4]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    相关资源
    最近更新 更多