【问题标题】:Pandas dataframe to dict with unique values from coloumn as keys and nested lists as valuesPandas 数据框以列中的唯一值作为键,嵌套列表作为值
【发布时间】:2019-02-24 16:47:03
【问题描述】:

我正在尝试将数据帧转换为字典,以列(列 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)]}

【问题讨论】:

    标签: pandas dictionary dataframe python-3.6 pandas-groupby


    【解决方案1】:

    使用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()
    

    【讨论】:

    • 感谢您的快速回答,它运行良好!我会尽快将您的答案标记为已接受(我必须再等 10 分钟 :))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 2020-03-19
    • 2022-10-30
    • 1970-01-01
    相关资源
    最近更新 更多