How to I factorize a list of tuples?

后端 未结 6 2014
春和景丽
春和景丽 2020-12-06 10:43

definition
factorize: Map each unique object into a unique integer. Typically, the range of integers mapped to is from zero to the n - 1 where n is

6条回答
  •  暖寄归人
    2020-12-06 10:55

    I don't know about timings, but a simple approach would be using numpy.unique along the respective axes.

    tups = [(1, 2), ('a', 'b'), (3, 4), ('c', 5), (6, 'd'), ('a', 'b'), (3, 4)]
    res = np.unique(tups, return_inverse=1, axis=0)
    print res
    

    which yields

    (array([['1', '2'],
           ['3', '4'],
           ['6', 'd'],
           ['a', 'b'],
           ['c', '5']],
          dtype='|S11'), array([0, 3, 1, 4, 2, 3, 1], dtype=int64))
    

    The array is automatically sorted, but that should not be a problem.

提交回复
热议问题