将Dataframe转换为字典,其中值为列表

7
假设我有一个数据框 df
Label1    Label2        Label3
key1      col1value1    col2value1
key2      col1value2    col2value2
key3      col1value3    col2value3


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

当我们有两列时,这个方法可以使用。

期望输出:

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

我能在Dataframe df上使用to_dict,将2个其他列作为列表的形式作为吗?
1个回答

4

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

1
你能解释一下第二种方法吗?我没听懂。"T"是什么意思? - Hypothetical Ninja
1
T 转置了数据帧。 - Karl D.
使用 T 是个好方法,我甚至没有意识到它会起作用,谢谢。 - Amon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接