【发布时间】:2017-07-05 15:46:05
【问题描述】:
鉴于此DataFrame:
import pandas as pd
first=[0,1,2,3,4]
second=[10.2,5.7,7.4,17.1,86.11]
third=['a','b','c','d','e']
fourth=['z','zz','zzz','zzzz','zzzzz']
df=pd.DataFrame({'first':first,'second':second,'third':third,'fourth':fourth})
df=df[['first','second','third','fourth']]
first second third fourth
0 0 10.20 a z
1 1 5.70 b zz
2 2 7.40 c zzz
3 3 17.10 d zzzz
4 4 86.11 e zzzzz
我可以使用 df 创建字典
a=df.set_index('first')['second'].to_dict()
这样我就可以决定什么是keys,什么是values。但是,如果您希望 values 成为列列表,例如 second AND third,该怎么办?
如果我试试这个
b=df.set_index('first')[['second','third']].to_dict()
我得到了一本奇怪的字典
{'second': {0: 10.199999999999999,
1: 5.7000000000000002,
2: 7.4000000000000004,
3: 17.100000000000001,
4: 86.109999999999999},
'third': {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}}
相反,我想要一个列表字典
{0: [10.199999999999999,a],
1: [5.7000000000000002,b],
2: [7.4000000000000004,c],
3: [17.100000000000001,d],
4: [86.109999999999999,e]}
如何处理?
【问题讨论】:
标签: python list pandas dictionary