How to replace elements in a list using dictionary lookup

前端 未结 5 1439
你的背包
你的背包 2020-12-03 10:37

Given this list

my_lst = [\'LAC\', \'HOU\', \'03/03 06:11 PM\', \'2.13\', \'1.80\', \'03/03 03:42 PM\']

I want to change its 0th

5条回答
  •  鱼传尺愫
    2020-12-03 11:34

    if you want something shorter, you can exploit the series function in pandas

    import pandas as pd
    A = ['A','B','A','C','D'] #list we want to replace with a dictionary lookup
    B = {'A':1,'B':2,'C':3,'D':4} #dictionary lookup, dict values in B will be mapped to entries in A
    C = (pd.Series(A)).map(B) #convert the list to a pandas series temporarily before mapping
    D = list(C) # we transform the mapped values (a series object) back to a list
    # entries in D = [1,2,1,3,4]
    

提交回复
热议问题