python - 如何在 python 中访问 numpy 结构化数组中的多个列值?
问题描述
我是 numpy 的新手,仍在学习它。我创建了一个结构化数组,如下所示:
name = ['Alice', 'Beth', 'Cathy', 'Dorothy']
studentid = [1,2,3,4]
score = [85.4, 90.4, 87.66, 78.9]
student_data = np.zeros(4, dtype={'names':('name', 'studentId', 'score'),
'formats':('U10', 'i4', 'f8')})
student_data['name'] = name
student_data['studentId'] = studentid
student_data['score']=score
为了得到分数大于 85 的人的名字,我写了这个:
student_data[student_data['score'] > 85]['name']
但是,如果我尝试检索另一列以及“名称”,则会收到错误消息:
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
例如,我尝试了以下方法:
student_data[student_data['score'] < 90]['name','studentid']
student_data[student_data['score'] < 90]['name']['studentid']
它们都导致错误:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-189-7ad7c151f0e3> in <module>
----> 1 student_data[student_data['score'] < 90]['name']['studentid']
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
谁能让我知道我在这里犯了什么错误以及如何在有条件的基础上检索多个列?
解决方案
您可以使用列数组访问:
student_data[student_data['score'] < 90][['name','studentid']]
输出:
array([('Alice', 1), ('Cathy', 3), ('Dorothy', 4)],
dtype={'names':['name','studentId'], 'formats':['<U10','<i4'], 'offsets':[0,40], 'itemsize':52})
推荐阅读
- javascript - AudioContext 的频率数据与 OfflineAudioContext 的频率数据相差很大
- javascript - 如果无效则捕获错误
- javascript - Module.exports 导出 nodejs 中的变量
- python - 为什么即使没有执行/'x' 权限也可以运行 python 脚本?
- python - 如何删除熊猫默认索引列?
- java - 如何使用 DateTimePicker 获取一周中某一天的名称
- javascript - Javascript 原型属性'
- node.js - Heroku Web 不断崩溃(托管 API)
- javascript - 将 math.round() 添加到用户输入填写的表单中,然后单击按钮查看输出
- android - 如何强制在 Firestore 中获取缓存的文档?我想在在线时获取缓存的文档