【问题标题】:Pandas Write to Excel rearranging columns based on alphabetic orderPandas Write to Excel 根据字母顺序重新排列列
【发布时间】:2018-07-25 12:14:42
【问题描述】:

我有一个格式如下的python dict

dict = {
        D:""
        B:""
        A:""
        C:""
}

但是,当我将此 dict 写入 excel 中的 csv 文件时,列会重新排列为

A B C D

当我写到 excel 时,如何保持我的 dict 在 python 中的顺序?

    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)

上面是写入excel的代码。

【问题讨论】:

  • 尝试使用 OrderedDict docs.python.org/3.6/library/…
  • 你想按什么顺序保存你的 dic?插入顺序??
  • 我想保持我在其中声明 dict 的顺序。 OrderedDict 不起作用,因为没有键或函数可以描述它们的排序方式。
  • @MWaz 没有ordereddict 和Python
  • @AntonvBR 当我将字典打印到控制台时,它的顺序正确。你的意思是没有办法有效地将这个字典“打印”到excel表上?

标签: python excel pandas


【解决方案1】:

与上面提到的相反,pandas.DataFrame.to_excel() 函数有一个参数,可让您设置将哪些订单列写入您的 Excel 工作表。 参数是

 columns=[listOfColumns]

对于我上面的例子,我会这样做

list_of_detected_words.to_excel(writer, "Sheet1", startrow=1, columns=[D,B,A,C] )

文档可以在以下链接中找到。

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多