Translate integers in a numpy array to a contiguous range 0…n

前端 未结 2 576
情深已故
情深已故 2020-12-04 03:42

I would like to translate arbitrary integers in a numpy array to a contiguous range 0...n, like this:

source: [2 3 4 5 4 3]
translating [2 3 4 5] -> [0 1          


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 04:44

    pandas.factorize is one method:

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

    Note: this returns a list, while np.unique will always return an np.ndarray.

提交回复
热议问题