Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字典中的地图列表_Python_List_Dictionary_Pandas - Fatal编程技术网

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

我是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]
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]
吗?是的,我已经实施了更改。这是个小错误。但这并没有改变答案!非常感谢。