熊猫数据帧到有序词典

Pav*_*dis 5 python dictionary pandas

有一个帖子,其中熊猫数据帧被转换为字典以供进一步处理.

执行此操作的代码是:

df = pd.read_excel(open('data/file.xlsx', 'rb'), sheetname="Sheet1")
dict = df.set_index('id').T.to_dict('dict')
Run Code Online (Sandbox Code Playgroud)

产生这样的东西: {column -> {index -> value}}

有没有一个快速的方法,而不是这个{column -> {index -> value}}得到这个:OrderedDict(column, value)作为一个返回值?

目前,我正在使用从pandas生成的字典,并将这些值逐个分配到有序字典中.这不是最佳方式,因为订单是乱码的

示例输入:这样的Excel文件:

Unique_id | column1 | column2 | column3 | column 4
1         | 3       | 4       | 43      | 90
2         | 54      | 6       | 43      | 54
Run Code Online (Sandbox Code Playgroud)

输出应该是一个有序的字典,如下所示:

{1:[3,4,43,90], 2:[54,6,43,54]}
Run Code Online (Sandbox Code Playgroud)

Abd*_*dou 5

您可以使用列中的OrderedDictwith 键以所需的顺序获取字典Unique_id。以下应作为说明:

from collections import OrderedDict

# Get the unordered dictionary
unordered_dict = df.set_index('Unique_id').T.to_dict('list')

 # Then order it
ordered_dict = OrderedDict((k,unordered_dict.get(k)) for k in df.Unique_id)
# OrderedDict([(1, [3, 4, 43, 90]), (2, [54, 6, 43, 54])])
Run Code Online (Sandbox Code Playgroud)

谢谢!