Python 为什么提取函数给出了错误的数组

Python 为什么提取函数给出了错误的数组,python,arrays,numpy,multidimensional-array,extract,Python,Arrays,Numpy,Multidimensional Array,Extract,我有一个2D数组,我只想返回一个新数组中的男学生。我想专门使用提取功能。但是,条件是正确的,但是提取函数给出了错误的输出 这会给出错误的输出,如下所示 [“女性”“男性”“大卫”] 但是,以不同的方式编写代码可以获得正确的输出。代码如下: # creating an a numpy array with the names of students along with their corresponding biological sex students=np.array([["ale

我有一个2D数组,我只想返回一个新数组中的男学生。我想专门使用提取功能。但是,条件是正确的,但是提取函数给出了错误的输出

这会给出错误的输出,如下所示

[“女性”“男性”“大卫”]

但是,以不同的方式编写代码可以获得正确的输出。代码如下:

# creating an a numpy array with the names of students along with their corresponding biological sex
students=np.array([["alexis", "female"],["alex", "male"], ["david", "non-binary"], ["samar", "male"], ["anweshan","male"]])

# creating a condition to check if a student is a male or not

con1 = students[0: , 1] == "male"
print(con1)
print(students[con1])
它给出以下输出

['alex'男'] [‘撒马尔’男'] ['anweshan'男']]


我想使用提取功能,所以您能告诉我哪里出错吗?

您的con数组的形状不同

con = students[: , 1] == "male"

con_same_shape = np.empty((5,2))

con_same_shape[:,0] = con
con_same_shape[:,1] = con

#creating a new array with only the male students
male_students = np.extract(con_same_shape, students)

print(male_students)
将返回:

['alex' 'male' 'samar' 'male' 'anweshan' 'male']

您可以像这样重塑输出:print(男学生。重塑((int)(len(男学生)/2),2)))
['alex' 'male' 'samar' 'male' 'anweshan' 'male']