Python 字典中的地图列表
我是python新手,为此已经阅读了许多页面 我知道熊猫数据帧具有以下映射功能:Python 字典中的地图列表,python,list,dictionary,pandas,Python,List,Dictionary,Pandas,我是python新手,为此已经阅读了许多页面 我知道熊猫数据帧具有以下映射功能: dictionary = {a:1, b:2, c:6} df['col_name'] = df.col_name.map(dictionary) #df is a pandas dictionary 如何对列表执行类似操作,即 mapped_list = list_to_be_mapped.map(dictionary) 在哪里 list_to_be_mapped = [a,a,b,c,c,a] mappe
dictionary = {a:1, b:2, c:6}
df['col_name'] = df.col_name.map(dictionary) #df is a pandas dictionary
如何对列表执行类似操作,即
mapped_list = list_to_be_mapped.map(dictionary)
在哪里
list_to_be_mapped = [a,a,b,c,c,a]
mapped_list = [1,1,2,6,6,1]
您可以使用
字典
的get
功能
list(map(dictionary.get, list_to_be_mapped))
IIUC您可以使用简单的
列表理解
:
[dictionary[key] for key in list_to_be_mapped]
In [51]: [dictionary[key] for key in list_to_be_mapped]
Out[51]: [1, 1, 2, 6, 6, 1]
如果您喜欢pandas
解决方案,您可以将列表转换为系列,然后使用与示例中相同的方法:
s = pd.Series(list_to_be_mapped)
In [53]: s
Out[53]:
0 a
1 a
2 b
3 c
4 c
5 a
dtype: object
In [55]: s.map(dictionary).tolist()
Out[55]: [1, 1, 2, 6, 6, 1]
如果您只想将这些值映射到词典中,我建议如下:
dictionary={'a':1,'b':2}
要映射的列表=['a',a',b',c',c',a']
[dictionary.get(a)if dictionary.get(a)else a for a in list\u to\u be\u映射]
返回
[1,1,2,'c','c',1]
根据您的决定,您的映射列表应该是[1,1,2,6,6,1]
吗?是的,我已经实施了更改。这是个小错误。但这并没有改变答案!非常感谢。