字典中的地图列表

时间:2016-03-31 09:29:17

标签: python list dictionary pandas

我是python的新手,并为此查看了很多页面。

我知道pandas数据框具有这种映射功能:

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]

3 个答案:

答案 0 :(得分:4)

您可以使用dictionary' get功能

list(map(dictionary.get, list_to_be_mapped))

答案 1 :(得分:2)

IIUC你可以使用简单的list comprehension

[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解决方案,可以将list_to_be_mapped转换为系列,然后使用与示例中相同的内容:

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]   

答案 2 :(得分:1)

如果您只想在字典中实际映射这些值,则建议以下内容:

dictionary = {'a': 1, 'b': 2}
list_to_be_mapped = ['a', 'a', 'b', 'c', 'c', 'a']
[dictionary.get(a) if dictionary.get(a) else a for a in list_to_be_mapped]

返回

[1, 1, 2, 'c', 'c', 1]