首页 > 解决方案 > Pandas 数据框以列中的唯一值作为键和嵌套列表作为值进行 dict

问题描述

我试图将数据框转换为字典,并使用来自列(col 3)的唯一值作为键。

由此:

  Col1   Col2   Col3
0  a       b      x
1  c       d      x
2  e       f      y
3  g       h      y

对此:

{x:[[a,b][c,d]],y:[[e,f],[g,h]]}

使用下面的代码,我得到了元组,这对我来说真的没有用。

new_dict = df.groupby('col3').apply(lambda x: list(zip(x['col1'],x['col2']))).to_dict()

输出:

{x:[(a,b),(c,d)],y:[(e,f),(g,h)]}

标签: pandasdictionarydataframepython-3.6pandas-groupby

解决方案


用于map列出或列出理解:

new_dict = (df.groupby('col3')
              .apply(lambda x: list(map(list, zip(x['col1'],x['col2']))))
              .to_dict())
print (new_dict)
{'x': [['a', 'b'], ['c', 'd']], 'y': [['e', 'f'], ['g', 'h']]}

new_dict = (df.groupby('col3')
              .apply(lambda x: [list(y) for y in zip(x['col1'],x['col2'])])
              .to_dict())

另一种解决方案是将每个组转换为二维数组并转换为list

new_dict = df.groupby('col3')['col1','col2'].apply(lambda x: x.values.tolist()).to_dict()

推荐阅读