【问题标题】:Why is the Extract function giving wrong array为什么提取函数给出错误的数组
【发布时间】:2021-08-18 04:34:47
【问题描述】:

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

# 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

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

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

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

['女''男''大卫']

但是,以不同的方式编写代码会产生正确的输出。代码如下:

# 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' '男']]

我想使用提取功能,请问我哪里出错了?

【问题讨论】:

    标签: python arrays numpy multidimensional-array extract


    【解决方案1】:

    你的 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(male_students.reshape(((int)(len(male_students)/2),2)))
    猜你喜欢
    • 2020-11-10
    • 2020-08-02
    • 1970-01-01
    • 2019-05-17
    • 2022-06-10
    • 2021-04-27
    • 2021-03-19
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多