使用pythonpandas将字典中的条目sorting为excel

我正在使用pandas将数据写入Excel文件。 我想转储数据,因为它是在一张纸和第二张纸我想要以sorting的方式。 图层是关键,权重是字典中的值。

例如sheet1应该有如下的表(未分类):

未分类的条目

而sheet2应该有sorting的条目:

在这里输入图像说明

我已经尝试OrderedDict

df1 = pd.DataFrame.from_dict(dict_weights, orient="index") df1.columns = ['weights'] df2 = pd.DataFrame.from_dict(collections.OrderedDict(dict_weights), orient="index") df2.columns = ['weights'] df1.to_excel(writer, sheet_name='sheet1') df2.to_excel(writer, sheet_name='sheet2', startcol=3) writer = pd.ExcelWriter(filename, engine='xlsxwriter') writer.save() 

问题是这样做sorting,但在两张表。 我只是想要在sheet2和sheet1中sorting数据,它应该保持未sorting。

预期产出:

工作表Sheet1

 Layer; weights T1_max_pool; 4 activation_9; 1 sum_9; 3 Merge_2; 4 activation_2; 1 T2_max_pool; 4 

Sheet2中

 Layer; weights activation_2; 1 activation_9; 1 Merge_2; 4 sum_9; 3 T1_max_pool; 4 T2_max_pool; 4 

有什么build议么?? :) 谢谢!

IIUIC,你需要在Layers列上使用sort_values

 In [503]: writer = pd.ExcelWriter('file.xlsx') In [504]: df.to_excel(writer, 'sheet1') In [505]: df.sort_values(by='Layers', ascending=True).to_excel(writer, 'sheet2') In [506]: writer.save() 

如果你不想索引,写入excel时使用index=False

把dict改成列表并使用:

 df1 = pd.DataFrame({'weights': list2}, index=list1) df2 = df1.sort_index() 

Dict有它自己的逻辑sorting键,如果你要print它,你会看到它不会按预期打印。