【问题标题】:Mapping dictionary onto dataframe when dictionary key is a list当字典键是列表时将字典映射到数据框
【发布时间】:2018-08-13 12:19:51
【问题描述】:

我有一本字典,其中的值是列表:

dict = {1: ['a','b'], 2:['c', 'd']}

我想将字典映射到我的数据框的 col1 上。

col1    
 a     
 c     

如果 col1 的值是我的字典的值之一,那么我想用字典键的值替换 col1 的值。

这样,我的数据框会变成:

col1
 1
 2

提前致谢

【问题讨论】:

  • 列表不可散列,您不能将它们用作字典键。可能您的意思是元组或其他可迭代和可散列的对象。
  • 抱歉,我把键和值弄混了。编辑了问题。
  • 好的,现在请用您尝试过的代码更新您的问题,并告诉我们您目前遇到的问题。
  • 您正在使用字典。从值到键,这不是字典的用例。

标签: python python-3.x pandas dictionary dataframe


【解决方案1】:

您也可以尝试使用stack + reset_indexset_indexmap

d = pd.DataFrame({1: ['a','b'], 2:['c', 'd']})
mapping = d.stack().reset_index().set_index(0)["level_1"]
s = pd.Series(['a', 'c'], name="col1")  
s.map(mapping)
0    1
1    2
Name: col1, dtype: int64

分步演示

d.stack()

0  1    a
   2    c
1  1    b
   2    d
dtype: object

d.stack().reset_index()

    level_0 level_1 0
0   0          1    a
1   0          2    c
2   1          1    b
3   1          2    d

d.stack().reset_index().set_index(0)

   level_0  level_1
0       
a       0        1
c       0        2
b       1        1
d       1        2

最后,我们选择level_1列作为我们的映射来传递map函数。

【讨论】:

    【解决方案2】:

    我会以正确的方式转换字典:

    mapping = {}
    for key, values in D.items():
        for item in values:
            mapping[item] = key
    

    然后

    df['col1'] = df['col1'].map(mapping)
    

    【讨论】:

      【解决方案3】:

      你的意思是这样吗???

      D = {1 : ['a', 'b'], 2 : ['c', 'd']}
      
      for key, value in D.items():
          for each in value:
              if each in D[key]:
                  print(each, "is in D[%s]" % key)
      

      o/p:

      a is in D[1]
      b is in D[1]
      c is in D[2]
      d is in D[2]
      

      【讨论】:

        猜你喜欢
        • 2018-05-03
        • 2021-07-14
        • 1970-01-01
        • 1970-01-01
        • 2010-12-31
        • 2021-06-26
        • 1970-01-01
        • 2018-09-21
        相关资源
        最近更新 更多