【问题标题】:Create a dictionary based on colums of a dataframe根据数据框的列创建字典
【发布时间】:2019-08-06 11:26:53
【问题描述】:

我有一个表单的数据框:

pandas as pd
df = pd.DataFrame({'col1': [1,2,3,4,5,6], 
                   'col2': ['A','A','B','C','D','D']}, 
                   index=['row1', 'row2','row3', 'row4','row5', 'row6'])

我想根据数据框 df 的值创建以下字典:

dict = {'A':[1,2], 'B':[3], 'C':[4], 'D':[5,6]}

【问题讨论】:

    标签: python python-3.x pandas dictionary


    【解决方案1】:

    通过GroupBy.apply将每组col1的值转换为列表,然后调用Series.to_dict

    d = df.groupby('col2')['col1'].apply(list).to_dict()
    print (d)
    {'A': [1, 2], 'B': [3], 'C': [4], 'D': [5, 6]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-24
      • 2019-10-20
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2020-11-12
      相关资源
      最近更新 更多