如何用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 inarray1againstarray2, returning a boolean array (Truewhen the element exists,Falseotherwise)..astype(int): Converts those boolean values to integers—sinceTruemaps to1andFalsemaps to0, 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
相关产品推荐
相关产品推荐

