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

如何基于第3、4列组合值筛选后向NumPy数组追加元素?

基于NumPy的数组去重追加实现

现有数组

import numpy as np

array = np.array(
        [[  1.,    1.,   82. , 177.,    0.,    0.,   -1. ],
         [  2.,    2.,   83. , 177.,    0.,    0.,    1. ],
         [  3.,    2.,   84. , 177.,    0.,    0.,    2. ],
         [  4.,    2.,   85. , 177.,    0.,    0.,    2. ],
         [  5.,    2.,   82.5, 177.,    0.,    0.,    2. ],
         [  6.,    2.,   83.5, 177.,    0.,    0.,    3. ]])

待追加的新元素数组

new_points = np.array(
   [[  7.,    2.,   82.5, 177.,    0.,    0.,    2. ],
    [  8.,    2.,   83.5, 177.,    0.,    0.,    4. ],
    [  9.,    2.,   84.5, 177.,    0.,    0.,    4. ],
    [ 10.,    2.,   84. , 177.,    0.,    0.,    4. ]])

需求

仅将第3、4列组合值未在原数组中出现的行追加到原数组中。

期望输出

array = np.array([
    [  1.,    1.,   82. , 177.,    0.,    0.,   -1. ],
    [  2.,    2.,   83. , 177.,    0.,    0.,    1. ],
    [  3.,    2.,   84. , 177.,    0.,    0.,    2. ],
    [  4.,    2.,   85. , 177.,    0.,    0.,    2. ],
    [  5.,    2.,   82.5, 177.,    0.,    0.,    2. ],
    [  6.,    2.,   83.5, 177.,    0.,    0.,    3. ],
    [  9.,    2.,   84.5, 177.,    0.,    0.,    4. ]
])

实现代码

# 提取原数组的第3、4列组合(索引从0开始,对应第3、4列是索引2和3)
original_pairs = array[:, [2, 3]]
# 提取新数组的对应列组合
new_pairs = new_points[:, [2, 3]]

# 将组合转换为元组集合,方便快速查找
original_set = set(tuple(pair) for pair in original_pairs)

# 筛选新数组中不在原集合里的行
filtered_new = new_points[[tuple(pair) not in original_set for pair in new_pairs]]

# 合并原数组和筛选后的新数组
result = np.vstack((array, filtered_new))

print(result)

代码说明

  1. 提取原数组和新数组中需要判断的第3、4列(索引2、3)的组合;
  2. 将原数组的组合转为集合,利用集合的O(1)查找特性提升效率;
  3. 遍历新数组的组合,筛选出未在原集合中的行;
  4. 使用np.vstack合并原数组和筛选后的新行,得到最终结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:31:13