【问题标题】:python binning sort considering the # of different values考虑到不同值的#的python分箱排序
【发布时间】:2020-04-09 00:22:06
【问题描述】:

如何高效地将列表转换为每个元素的值顺序?

例如:

input1: [0,5,2,4,2] -> output1: [0,3,1,2,1] #(总共有4个不同的值)

input2: [45,7,1024,45] -> output2: [1,0,2,1] #(3个不同的值)

input3: [5,1,2] -> output3: [2,0,1] #(3个不同的值)

我已经尝试过 np.digitize(array, bins) 但无法定义 bin 以满足此任务。

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以使用pd.factorize:

    import pandas as pd
    lst = [0, 5, 2, 4, 2]
    
    order_of_values, uniques = pd.factorize(lst, sort=True)
    print(order_of_values)  # [0, 3, 1, 2, 1]
    

    【讨论】:

      【解决方案2】:

      Daniel 给出了适合您想要的确切输出的答案。另一个选项是来自 numpy 的 np.argsort,它将提供唯一索引。

      import numpy as np
      
      lst = [0,5,2,4,2]
      idx = np.argsort(lst)
      print(idx)
      # array([0, 2, 4, 3, 1])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-10
        • 2012-06-28
        • 2018-12-05
        • 1970-01-01
        • 2014-12-13
        • 1970-01-01
        相关资源
        最近更新 更多