pandas mapping list to dict items for new column

久未见 提交于 2021-02-10 14:41:05

问题


i have df like:

col_A
[1,2,3]
[2,3]
[1,3]

and dict like:

dd = {1: "Soccer", 2: "Cricket", 3: "Hockey"}

how can i create a new column col_B like:

col_A      col_B
[1,2,3]    ["Soccer", "Cricket", "Hockey"]
[2,3]      ["Cricket", "Hockey"]
[1,3]      ["Soccer", "Hockey"]

tried something like:

df['sports'] = df['col_A'].map(dd)

got error:

TypeError: unhashable type: 'list'

回答1:


You can use list comprehension with if for filter out not matched values:

df['sports'] = df['col_A'].map(lambda x: [dd[y] for y in x if y in dd])

Or replace to None if no match:

df['sports'] = df['col_A'].map(lambda x: [dd.get(y, None) for y in x])

Or return same values if no match:

df['sports'] = df['col_A'].map(lambda x: [dd.get(y, y) for y in x])

Sample:

df['sports1'] = df['col_A'].map(lambda x: [dd[y] for y in x if y in dd])
df['sports2'] = df['col_A'].map(lambda x: [dd.get(y, None) for y in x])
df['sports3'] = df['col_A'].map(lambda x: [dd.get(y, y) for y in x])
print (df)
          col_A                    sports1                          sports2  \
0  [1, 2, 3, 5]  [Soccer, Cricket, Hockey]  [Soccer, Cricket, Hockey, None]   
1        [2, 3]          [Cricket, Hockey]                [Cricket, Hockey]   
2        [1, 3]           [Soccer, Hockey]                 [Soccer, Hockey]   

                        sports3  
0  [Soccer, Cricket, Hockey, 5]  
1             [Cricket, Hockey]  
2              [Soccer, Hockey] 



回答2:


col_A=[[1,2,3],[2,3],[1,3]]

df=pd.DataFrame({'col_A':col_A})

dictLkup = {1: "Soccer", 2: "Cricket", 3: "Hockey"}

def lookupfunc(mylist):
    retlist=[] 
    [retlist.append(dictLkup[x]) for x in mylist]
    return(retlist)

df['col_B']=df['col_A'].apply(lambda x: lookupfunc(x))

 print(df.head())


来源:https://stackoverflow.com/questions/65954374/pandas-mapping-list-to-dict-items-for-new-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!