【问题标题】:how to write into excel with the header follow exactly the dictionary keys?如何使用标题完全按照字典键写入excel?
【发布时间】:2020-11-09 06:21:42
【问题描述】:

我确实有一个包含 20000++ 个字典的列表,其中包含 59 个键和值。我需要将字典导出到 excel 中。下面是我使用 pandas 写入 excel 的脚本,但问题是标题没有遵循字典中键的正确位置。以下只是列表的一部分。

new_d=[{'file': '1_2', 'name': 'paul', 'role': 'engineer',.....},
       {'file': '1_2', 'name': 'smith', 'role': 'engineer',....},
       {'file': '1_2', 'name': 'mei', 'role': 'engineer',.....}
        . 
        .
        . ]

这是我使用 pandas 将列表导出到 excel 中的代码

ccf_df=pd.DataFrame(a)
writer=pd.ExcelWriter('file.xlsx',engine='xlsxwriter')
ccf_df.to_excel(writer,sheet_name='FCC')

很遗憾,excel 文件中的输出没有遵循字典中键的正确位置。

应该是file|name|role|actor|time|.....,但输出是actor|file|time|role|name|.....

【问题讨论】:

  • 这可能是因为python的字典不保留键顺序。也许试试 OrderedDict (它确实保留了键顺序),看看这是否有所作为?在此处查看文档:docs.python.org/3/library/collections.html
  • 但是df.to_excel("data.xlsx", columns=[A,B,C])期间可以指定列的顺序

标签: python excel pandas dictionary


【解决方案1】:

您可以通过提供columns=[list of columns] 来强制 pandas excel 编写器按照您想要的方式保持列的顺序 ccf_df.to_excel(writer,sheet_name='CCF', columns=[list of columns])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多