Pandas 根据字母顺序写入 Excel 重新排列列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48795387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas Write to Excel rearranging columns based on alphabetic order
提问by M Waz
I have a python dict that has the format
我有一个具有格式的python dict
dict = {
D:""
B:""
A:""
C:""
}
However, when I write this dict to a csv file in excel, the columns are rearranged to
但是,当我将此 dict 写入 excel 中的 csv 文件时,列被重新排列为
A B C D
How do I keep the order of my dict in python when I write to excel?
当我写到 excel 时,如何在 python 中保持我的 dict 的顺序?
writer = pd.ExcelWriter('list_of_detected_words.xlsx', engine='xlsxwriter')
list_of_detected_words = pd.DataFrame.from_records(form_info)
list_of_detected_words.to_excel(writer, "Sheet1",startrow=1)
Above is the code that writes to excel.
以上是写入excel的代码。
回答by M Waz
Contrary to what was mentioned above, the pandas.DataFrame.to_excel() function has a parameter that lets you set which order columns are written to your excel sheet. The parameter is
与上面提到的相反,pandas.DataFrame.to_excel() 函数有一个参数,可让您设置将哪些订单列写入 Excel 工作表。参数是
columns=[listOfColumns]
For my example above I would do
对于我上面的例子,我会做
list_of_detected_words.to_excel(writer, "Sheet1", startrow=1, columns=[D,B,A,C] )
Documentation can be found on the following link.
可以在以下链接中找到文档。
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html