【问题标题】:Convert Dataframe to a Dictionary with List Values将 Dataframe 转换为具有列表值的字典
【发布时间】:2014-06-23 21:55:48
【问题描述】:

假设我有一个 Dataframe df:

Label1    Label2        Label3
key1      col1value1    col2value1
key2      col1value2    col2value2
key3      col1value3    col2value3


dict1 = df.set_index('Label1').to_dict() 

这在我们有 2 列时有效..

预期输出:

my_dict = {key1: [col1value1,col2value1] , key2: [ col1value2,col2value2] , key3:[col1value3,col2value3] }

我可以在 Dataframe df 上使用to_dict 以 list 的形式将 2 个其他列 的键作为 值 ??

【问题讨论】:

    标签: python python-2.7 dictionary pandas dataframe


    【解决方案1】:

    你可以使用字典理解和 iterrows:

    print {key:row.tolist() for key,row in df.set_index('Label1').iterrows()}
    
    {'key3': ['col1value3', 'col2value3'],
     'key2': ['col1value2', 'col2value2'], 
     'key1': ['col1value1', 'col2value1']}
    

    另外,我认为以下方法也可以:

    df = df.set_index('Label1')
    print df.T.to_dict(outtype='list')
    
    {'key3': ['col1value3', 'col2value3'],
     'key2': ['col1value2', 'col2value2'],
     'key1': ['col1value1', 'col2value1']}
    

    2017 年秋季更新; outtype 不再是关键字参数。改用 orient:

    In [11]: df.T.to_dict(orient='list')
    Out[11]: 
    {'key1': ['col1value1', 'col2value1'],
     'key2': ['col1value2', 'col2value2'],
     'key3': ['col1value3', 'col2value3']}
    

    【讨论】:

    • 你能解释一下第二种方法吗,我不明白。 “T”有什么作用?
    • T 转置数据帧。
    • 使用T 的好方法,甚至没有意识到这会奏效,谢谢。
    猜你喜欢
    • 2018-04-22
    • 2018-07-25
    • 2014-01-05
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多