本文介绍了 pandas 映射列表到新列的字典项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有df,例如:

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

和类似的字典:

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

如何创建像这样的新列col_B:

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"]

尝试了以下内容:

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

得到错误:

TypeError: unhashable type: 'list'

推荐答案

您可以将列表理解与 if 一起使用,以过滤出不匹配的值:

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])

或如果没有匹配项,则替换为 None :

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])

示例:

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] 

这篇关于 pandas 映射列表到新列的字典项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 04:28