【问题标题】:how to print values in an array in order after sorted indexes in python?如何在python中排序索引后按顺序打印数组中的值?
【发布时间】:2018-07-16 04:08:19
【问题描述】:

假设我有 2 个向量,高度和年龄。

ages = np.random.randint(low=20, high=60, size=10)
heights = np.random.randint(low=150, high=200, size=10)

年龄向量的每个值将对应一个高度值。我想按顺序打印年龄及其相应的高度。我相信我必须先对年龄索引进行排序

a = np.argsort(ages)

以及一些如何将该索引的顺序分配给年龄值。我想过使用循环,但我不知道如何?有人可以帮帮我吗?谢谢

【问题讨论】:

    标签: python sorting numpy


    【解决方案1】:

    np.argsort 函数以排序顺序为您提供数组的索引 -- 使用索引 --

    >>> ages = np.random.randint(low=20, high=60, size=10)
    >>> heights = np.random.randint(low=150, high=200, size=10)
    >>> ages
    array([44, 35, 37, 39, 48, 24, 22, 25, 22, 59])
    >>> heights
    array([179, 195, 158, 189, 183, 185, 186, 187, 161, 175])
    >>> ia = np.argsort(ages)
    >>> ages[ia]
    array([22, 22, 24, 25, 35, 37, 39, 44, 48, 59])
    >>> heights[ia]
    array([186, 161, 185, 187, 195, 158, 189, 179, 183, 175])
    

    注意,在这种情况下,您可能会考虑使用结构化数组:

    >>> mytype = np.dtype([('age',int), ('height', int)])
    >>> data = np.array(list(zip(ages, heights)), dtype=mytype)
    >>> data
    array([(44, 179), (35, 195), (37, 158), (39, 189), (48, 183), (24, 185),
           (22, 186), (25, 187), (22, 161), (59, 175)],
          dtype=[('age', '<i8'), ('height', '<i8')])
    

    现在您可以将“订单”参数传递给.sort

    >>> data.sort(order='age')
    >>> data
    array([(22, 161), (22, 186), (24, 185), (25, 187), (35, 195), (37, 158),
           (39, 189), (44, 179), (48, 183), (59, 175)],
          dtype=[('age', '<i8'), ('height', '<i8')])
    

    但是,这并不完全等同于上面,因为它使用高度来打破关系,所以请注意,(22, 161)(22, 186) 之前。

    【讨论】:

    • 太棒了,我想我必须使用循环将年龄中的每个索引替换为排序索引并对高度执行相同操作
    • @EddieVu 不,你几乎不需要循环。这就是 numpy 向量化操作的重点。
    【解决方案2】:

    您可以使用纯 python 做到这一点。如果您要对所有唯一值进行排序,则可以使用临时字典:

    ages = [2,4,1,6]
    heights = [3,4,2,6]
    
    temp = {}
    for age, height in zip(ages, heights):
        temp[age] = height
    
    for key in sorted(temp):
        print(key, temp[key])
    

    如果你有非唯一值,那么你可以使用一个临时数组:

    ages = [2,4,1,6,2]
    heights = [3,4,2,6,7]
    
    temp = []
    for age, height in zip(ages, heights):
         temp.append((age, height))
    
    for age, height in sorted(temp):
         print(age, height)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多