将数据帧转换为具有列表值的字典

时间:2014-05-07 04:58:18

标签: python python-2.7 dictionary pandas dataframe

假设我有一个 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] }

我是否可以在数据框 df 上使用to_dict其他列的密钥以的形式>列表 ??

1 个答案:

答案 0 :(得分:2)

你可以使用词典理解和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']}