gpt4 book ai didi

python - Pandas:to_excel():如何将时间表示为 TimeSeries 索引的格式?

转载 作者:行者123 更新时间:2023-11-28 17:27:16 27 4
gpt4 key购买 nike

我有一个带有 index 的 DataFrame:

Index([00:00:00, 00:05:00, 00:10:00, 00:15:00, 00:20:00, 00:25:00, 00:30:00,
00:35:00, 00:40:00, 00:45:00,
...
23:10:00, 23:15:00, 23:20:00, 23:25:00, 23:30:00, 23:35:00, 23:40:00,
23:45:00, 23:50:00, 23:55:00],
dtype='object', length=288)

我把这个df写成excel如下:

writer = pd.ExcelWriter("output.xlsx")
df.set_index(index, inplace=True)
df.to_excel(writer, sheet_name="Days")
writer.save()

但是当我打开并查看 Excel 内容时,我看到了这个:

enter image description here

索引显示为 float 。

如果我将 Excel 单元格格式化为时间,那么我会看到这样的结果:

enter image description here

我不喜欢每次打开工作表时都手动设置格式,那么,在创建 Excel 文件时有没有一种表达格式的方法?

最佳答案

如果您使用 XlsxWriter 作为 Pandas 的引擎,您可以通过这种方式设置特定列的格式:

workbook = writer.book
worksheet = writer.sheets['Days']
timeFormat = workbook.add_format({'num_format': 'h:mm:ss'})
worksheet.set_column('A:A', None, timeFormat)

Source

关于python - Pandas:to_excel():如何将时间表示为 TimeSeries 索引的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37872414/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com