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

如何用单行代码获取NumPy数组的索引补集?

获取NumPy数组索引的补集(单行实现)

给定数组和索引:

import numpy as np
my_array = np.array([ [1,2], [3,4], [5,6], [7,8] ])
indices = np.array([0,2])

直接用my_array[~indices]无法得到补集,因为~是按位取反操作,会把[0,2]转换成[-1,-3],对应数组的倒数行,不是预期的索引补集。

单行实现补集获取的代码:

my_array[np.setdiff1d(np.arange(my_array.shape[0]), indices)]

执行后得到结果:

array([[3, 4],
       [7, 8]])

逻辑说明

  • np.arange(my_array.shape[0])生成数组所有行的索引:[0,1,2,3]
  • np.setdiff1d(a, b)返回在a中但不在b里的元素,即补集索引[1,3]
  • 用补集索引直接切片数组,得到目标结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:55:36