用于在Excel中导出的嵌套字典顺序或pandas列顺序

时间:2018-05-03 07:49:54

标签: python pandas sorting dictionary

我想将嵌套字典中包含的某些数据导出到PD数据帧,然后导出到Excel:

counter=0
for m in [3]:
for column, wind_speed in enumerate(wind_speeds):
    for row,ti in enumerate(TIs): 
        if ~np.isnan(Mx_m_3[row,column]): 
            exec("dtb_dict.update({"+str(counter)+":{'case': '12', 
'WindSpeed': wind_speed, 'TI':ti, 
list_of_variables[0]:"+list_of_variables[0]+"[row,column], 
list_of_variables[1]:"+list_of_variables[1]+"[row,column]}})")
            counter+=1


a=pd.DataFrame.from_dict({i: dtb_dict[i]
                       for i in dtb_dict.keys() 
                       for j in dtb_dict[i].keys()},
                   orient='index')


writer = pd.ExcelWriter('output.xlsx', engine='xlsxwriter')

我想要一个包含列的数据框,例如wind,speed,ti,list_of_variables [0],list_of_variables [1]

我得到: case,wind,speed,list_of_variables [1],list_of_variables [0],ti

有没有办法指定嵌套字典的顺序或重新排列数据框?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以轻松地为pandas DataFrame执行此操作。

假设我们从

开始
a = pd.DataFrame({"case": list(range(10)), "wind,speed": list(range(10)), "list_of_variables[1]": list(range(10)), "list_of_variables[0]":list(range(10)), "ti": list(range(10))})

然后

a = a[["case", "wind,speed", "ti", "list_of_variables[0]", "list_of_variables[1]"]]

会根据您的意愿对列进行排序。