【问题标题】:Sort Structured Numpy Array On Multiple Columns In Different Order以不同的顺序对多列上的结构化 Numpy 数组进行排序
【发布时间】:2019-03-04 13:03:33
【问题描述】:

我有一个结构化的 numpy 数组:

dtype = [('price', float), ('counter', int)]
values = [(35, 1), (36, 2),
          (36, 3)]
a = np.array(values, dtype=dtype)

如果价格相等,我想按价格排序,然后按计数器排序:

a_sorted = np.sort(a, order=['price', 'counter'])[::-1]

我需要按降序排列的价格,当价格相等时,考虑按升序排列计数器。在上面的示例中,价格和计数器均按降序排列。

我得到的是:

a_sorted: [(36., 3), (36., 2), (35., 1)]

我需要的是:

 a_sorted: [(36., 2), (36., 3), (35., 1)]

【问题讨论】:

    标签: python arrays sorting numpy numpy-ndarray


    【解决方案1】:

    你可以使用np.lexsort:

    a_sorted = a[np.lexsort((a['counter'], -a['price']))]
    

    结果:

    array([(36.0, 2), (36.0, 3), (35.0, 1)], 
          dtype=[('price', '<f8'), ('counter', '<i4')])
    

    请记住顺序是相反的,即首先由-a['price'] 执行排序。否定处理“降序”方面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 2013-10-09
      相关资源
      最近更新 更多