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

如何用NumPy判断数组元素是否在另一数组中并生成标识行

Check if NumPy Array Elements Exist in Another Array & Create Indicator Row

Hey there, let's tackle this problem straightforwardly. You need to generate an indicator row where each position is 1 if the corresponding element in array1 exists in array2, and 0 otherwise—then stack that row below the original array. Here's a clean, efficient way to do it with NumPy:

Solution Code

import numpy as np

# Your input arrays
array1 = np.array([1,2,3,4,5,10,12,13])
array2 = np.array([4,6,3,5,0])

# Generate the indicator array
indicator = np.isin(array1, array2).astype(int)

# Stack the original array and indicator into a 2D array
result = np.vstack([array1, indicator])

print(result)

How It Works

Let's break down each step:

  • np.isin(array1, array2): This function checks every element in array1 against array2, returning a boolean array (True when the element exists, False otherwise).
  • .astype(int): Converts those boolean values to integers—since True maps to 1 and False maps to 0, this gives us exactly the indicator we need.
  • np.vstack([array1, indicator]): Vertically stacks the original 1D array and the indicator row into a single 2D array, matching your expected output perfectly.

Output

When you run the code, you'll get:

[[ 1  2  3  4  5 10 12 13]
 [ 0  0  1  1  1  0  0  0]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:12:27