Python Map List of Strings to Integer List

后端 未结 9 1236
猫巷女王i
猫巷女王i 2020-12-31 23:05

Let\'s say I have a list

l = [\'michael\',\'michael\',\'alice\',\'carter\']

I want to map it to the following:

k = [1,1,2,3         


        
相关标签:
9条回答
  • 2020-12-31 23:44

    How about using Pandas?

    import pandas as pd
    l = ['michael','michael','alice','carter']
    pd.Series(l).astype('category').cat.codes.values
    
    0 讨论(0)
  • 2020-12-31 23:44

    To map list of integers to list of strings I would use a dictionary, for example:

    > name_number = {'michael':1, 'michael':1, 'alice':2, 'carter':3}
    > print len(name_number)
      3
    > print name_number['alice']
      2
    

    Note that len(name_number) is 3, because duplicate keys are not allowed.

    0 讨论(0)
  • 2020-12-31 23:44

    can do it pretty easy without a function :

    j - list()    
    for i in range (len(l)) : 
       j.append((l[i],k[i]))
    
    0 讨论(0)
提交回复
热议问题