代码之家  ›  专栏  ›  技术社区  ›  Metadata

如何在python中访问numpy结构数组中的多个列值?

  •  0
  • Metadata  · 技术社区  · 6 年前

    我创建了一个结构化数组,如下所示:

    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
    

    student_data[student_data['score'] > 85]['name']
    

    但是,如果我试图检索另一个列和“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
    

    有人能告诉我我在这里犯了什么错误吗?我怎样才能有条件地检索多个列?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Quang Hoang    6 年前

    您可以使用列数组进行访问:

    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})
    
        2
  •  1
  •   sushanth    6 年前

    你可以用 np.where

    print(student_data[np.where(student_data['score'] < 90)][['name', 'studentId']])
    
    [('Alice', 1) ('Cathy', 3) ('Dorothy', 4)]