Python中如何根据学生姓名提取对应成绩数组的行?
解决方法
先说说你之前代码的问题:
np.concatenate会把字符串数组和数值数组强行转成同一种类型(这里是字符串),导致grades里的数字都变成了字符串,完全没法正常做数值操作。- NumPy数组不能直接用元素值(比如'Alex')当索引,得用布尔掩码或者位置下标来筛选。
下面给两种简单的正确实现方式:
方法一:布尔掩码筛选(最推荐)
用np.isin直接生成筛选条件,一步到位提取目标行:
import numpy as np students = np.array(['Alex', 'Rich', 'Anthony', 'Len', 'Mark']) grades = np.array([[85, 44], [63, 19], [47, 95], [30, 67], [33, 16]]) # 生成布尔数组:对应位置是'Alex'或'Mark'就为True filter_mask = np.isin(students, ['Alex', 'Mark']) # 用掩码筛选grades的对应行 target_grades = grades[filter_mask] print(target_grades) # 输出结果: # [[85 44] # [33 16]]
方法二:先找索引再提取
如果你想先明确找到目标学生的位置,再提取成绩:
import numpy as np students = np.array(['Alex', 'Rich', 'Anthony', 'Len', 'Mark']) grades = np.array([[85, 44], [63, 19], [47, 95], [30, 67], [33, 16]]) # 找到'Alex'和'Mark'的索引位置 alex_pos = np.where(students == 'Alex')[0][0] mark_pos = np.where(students == 'Mark')[0][0] # 根据索引提取对应行 target_grades = grades[[alex_pos, mark_pos]] print(target_grades) # 输出和上面一样
新手优先用方法一,np.isin能轻松处理多个目标值,代码更简洁。另外别再把字符串和数值数组拼接了,会搞乱数据类型,后续想算个平均分都麻烦。
内容的提问来源于stack exchange,提问作者a_westie99
相关产品推荐
相关产品推荐

