【问题标题】:Map list from dictionaries字典中的地图列表
【发布时间】:2016-07-19 16:06:49
【问题描述】:

我是 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]

【问题讨论】:

  • 根据您的字典,您的mapped_list 应该是[1, 1, 2, 6, 6, 1] 吗?
  • 是的,我已经实施了这些更改。这是一个小错字。但这并不会改变答案!谢谢。

标签: python list dictionary pandas


【解决方案1】:

你可以使用dictionaryget函数

list(map(dictionary.get, list_to_be_mapped))

【讨论】:

    【解决方案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]   
    

    【讨论】:

      【解决方案3】:

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

      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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-17
        • 2023-03-30
        • 2021-10-17
        • 1970-01-01
        • 1970-01-01
        • 2019-01-14
        • 2014-10-15
        相关资源
        最近更新 更多