Python Pandas - 如何使用to_dict()将sort_values输出转换为字典

时间:2018-01-30 16:27:13

标签: python pandas dictionary

这是我的代码

from pandas import *
from collections import OrderedDict

def STC_define(stc_file, sheet):
    stc = stc_file
    stc_sheetname = sheet
    stc_xlsx = ExcelFile(stc)
    stc_df = stc_xlsx.parse(stc_sheetname, convert_float=True)
    stc_dic = stc_df.to_dict()
    return stc_df

stc_file = 'test1.xlsx'
sheet = 'Sheet1'
df = STC_define(stc_file, sheet)
print df

输出**

   Floor  Room  Code
0     G     2    A567
1     K    10    A567
2     F     5    A567
3     D     8    A555
4     B     8    A555
5     H     3    A567

使用sort_values排序时,我得到了正确的输出。我现在要做的是使用to_dict()将排序后的值转换为字典。

df = df.sort_values(by=['Floor'])
dic = df.to_dict()
print df
print dic

输出**

   Floor  Room  Code
4     B     8  A555
3     D     8  A555
2     F     5  A567
0     G     2  A567
5     H     3  A567
1     K    10  A567

{u'Code': {0L: u'A567', 1L: u'A567', 2L: u'A567', 3L: u'A555', 4L: u'A555', 5L: u'A567'}, u'Room': {0L: 2L, 1L: 10L, 2L: 5L, 3L: 8L, 4L: 8L, 5L: 3L}, u'Floor': {0L: u'G', 1L: u'K', 2L: u'F', 3L: u'D', 4L: u'B', 5L: u'H'}}

是否有一种方法可以使用to_dict()来排序转换为字典,还是有另一种方法可以将数据帧转换为字典?我希望字典格式保持不变

1 个答案:

答案 0 :(得分:1)

不,你不能订购Python字典。

Python dictionaries are unordered:

  

最好将字典视为一组无序的键:值对,并要求键是唯一的(在一个字典中)。一对大括号创建一个空字典:{}。在括号内放置以逗号分隔的键:值对列表,将初始键:值对添加到字典中;这也是字典在输出上的写法。