You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何依据B1、D1的nan元素同步删除所有数组对应索引元素

错误原因

你当前的代码是分别对三个数组单独过滤非NaN值,没有按索引位置做对齐判断,同时嵌套的列表推导逻辑错误,生成了三维嵌套结构,完全不符合「同一索引位置只要B1或D1存在NaN就同步删除三个数组对应位置元素」的需求。

正确实现(基于numpy,符合你已引入numpy的使用习惯)

首先修正原始数组的定义(原代码列表元素缺失逗号,且先转为numpy数组方便按掩码索引):

import numpy as np

# 先将原始列表转为numpy数组,修正元素分隔逗号
V1 = np.array([7.98083, 16.5216, 18.4423, 15.644, 15.539, 15.89, 12.092, 19.4274, 14.953, 15.943, 13.665, 16.777, 15.901, 13.477, 15.563, 11.217, 15.415, 16.023, 16.855, 14.851, 14.419, 12.345, 14.234, 16.515, 16.148])
B1 = np.array([8.75, np.nan, 20.483, 16.845, 16.571, 16.972, 13.873, np.nan, 16.238, 16.625, 14.715, np.nan, 16.743, 14.676, np.nan, 12.578, 16.459, 17.148, 20.313, 15.801, 15.462, 13.998, 15.421, 20.129, 18.055])
D1 = np.array([132.024, 3334.64, np.nan, 1909.26, 4256.32, 2720.97, 1926.14, np.nan, 3612.81, 5313.58, 1444.71, 2978.38, 2400.28, 999.693, 3132.71, 887.126, 4574.86, 1845.27, 3905.06, 2889.84, 1687.51, 2511.17, 3176.06, 2698.26, 4980.22])

# 构造保留索引的掩码:同一位置B1和D1都不是NaN才保留
mask = ~(np.isnan(B1) | np.isnan(D1))

# 用掩码分别过滤三个数组
V = V1[mask]
B = B1[mask]
D = D1[mask]

# 验证长度
print(len(V), len(B), len(D)) # 输出 21 21 21

如果需要输出为普通Python列表,在过滤后加.tolist()方法即可:

V = V1[mask].tolist()
B = B1[mask].tolist()
D = D1[mask].tolist()

纯Python实现(不依赖numpy)

如果不想用numpy,可以按索引遍历判断:

import math # 也可以利用nan不等于自身的特性判断,无需引入math

V1 = [7.98083, 16.5216, 18.4423, 15.644, 15.539, 15.89, 12.092, 19.4274, 14.953, 15.943, 13.665, 16.777, 15.901, 13.477, 15.563, 11.217, 15.415, 16.023, 16.855, 14.851, 14.419, 12.345, 14.234, 16.515, 16.148]
B1 = [8.75, float('nan'), 20.483, 16.845, 16.571, 16.972, 13.873, float('nan'), 16.238, 16.625, 14.715, float('nan'), 16.743, 14.676, float('nan'), 12.578, 16.459, 17.148, 20.313, 15.801, 15.462, 13.998, 15.421, 20.129, 18.055]
D1 = [132.024, 3334.64, float('nan'), 1909.26, 4256.32, 2720.97, 1926.14, float('nan'), 3612.81, 5313.58, 1444.71, 2978.38, 2400.28, 999.693, 3132.71, 887.126, 4574.86, 1845.27, 3905.06, 2889.84, 1687.51, 2511.17, 3176.06, 2698.26, 4980.22]

V, B, D = [], [], []
for v, b, d in zip(V1, B1, D1):
    # 只要b或d是nan就跳过该位置
    if not (math.isnan(b) or math.isnan(d)):
        V.append(v)
        B.append(b)
        D.append(d)

print(len(V), len(B), len(D)) # 输出 21 21 21

内容的提问来源于stack exchange,提问作者RKhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:51:02