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

Hyp*_*nja 6 python dictionary dataframe python-2.7 pandas

假设我有一个Dataframe df

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


dict1 = df.set_index('Label1').to_dict() 
Run Code Online (Sandbox Code Playgroud)

当我们有 2 列时,这有效..

预期输出:

my_dict = {key1: [col1value1,col2value1] , key2: [ col1value2,col2value2] , key3:[col1value3,col2value3] }
Run Code Online (Sandbox Code Playgroud)

我可以to_dict在 Dataframe df上使用一个带有2 个其他列的键作为列表形式的吗??

Kar*_* D. 4

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

print {key:row.tolist() for key,row in df.set_index('Label1').iterrows()}

{'key3': ['col1value3', 'col2value3'],
 'key2': ['col1value2', 'col2value2'], 
 'key1': ['col1value1', 'col2value1']}
Run Code Online (Sandbox Code Playgroud)

另外,我认为以下内容也将起作用:

df = df.set_index('Label1')
print df.T.to_dict(outtype='list')

{'key3': ['col1value3', 'col2value3'],
 'key2': ['col1value2', 'col2value2'],
 'key1': ['col1value1', 'col2value1']}
Run Code Online (Sandbox Code Playgroud)

截至 2017 年秋季更新;outtype不再是关键字参数。使用东方代替:

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