Pandas 数据框以列中的唯一值作为键和嵌套列表作为值进行字典

Lou*_*vre 3 dictionary dataframe pandas python-3.6 pandas-groupby

我试图将数据帧转换为字典,以列(列 3)中的唯一值作为键。

由此:

  Col1   Col2   Col3
0  a       b      x
1  c       d      x
2  e       f      y
3  g       h      y
Run Code Online (Sandbox Code Playgroud)

对此:

{x:[[a,b][c,d]],y:[[e,f],[g,h]]}
Run Code Online (Sandbox Code Playgroud)

使用以下代码,我得到了元组,这对我来说真的不起作用。

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

输出:

{x:[(a,b),(c,d)],y:[(e,f),(g,h)]}
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 7

使用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']]}
Run Code Online (Sandbox Code Playgroud)
new_dict = (df.groupby('col3')
              .apply(lambda x: [list(y) for y in zip(x['col1'],x['col2'])])
              .to_dict())
Run Code Online (Sandbox Code Playgroud)

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

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

  • 感谢您的快速答复,它运行完美!我会尽快将您的答案标记为已接受(我必须再等 10 分钟 :)) (2认同)