我有一个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内容时,我看到了这一点:
索引显示为浮点数。
如果我将Excel单元格格式化为时间,那么我会这样看:
我不喜欢每次打开它时手动格式化页面,所以,有没有办法在创建Excel文件时表示格式?
答案 0 :(得分:1)
如果您使用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)
答案 1 :(得分:1)
您可以使用datetime_format
函数的pandas.ExcelWriter()
参数来执行此操作,但您需要先将索引转换为datetime
类型:
In [104]: df
Out[104]:
val
00:00:00 4
00:05:00 9
00:10:00 7
00:15:00 7
00:20:00 7
00:25:00 0
00:30:00 7
00:35:00 4
00:40:00 3
00:45:00 1
In [105]: df.index = pd.to_datetime(df.index, format='%H:%M:%S')
In [106]: df
Out[106]:
val
1900-01-01 00:00:00 4
1900-01-01 00:05:00 9
1900-01-01 00:10:00 7
1900-01-01 00:15:00 7
1900-01-01 00:20:00 7
1900-01-01 00:25:00 0
1900-01-01 00:30:00 7
1900-01-01 00:35:00 4
1900-01-01 00:40:00 3
1900-01-01 00:45:00 1
In [107]: writer = pd.ExcelWriter("d:/temp/output.xlsx", datetime_format='hh:mm:ss')
In [108]: df.to_excel(writer)
In [109]: writer.save()
如果您不想更改索引 - 您可以在写入Excel文件时“即时”执行此操作,从而保留原始索引:
df.set_index(pd.to_datetime(df.index, format='%H:%M:%S')).to_excel(writer)
生成的Excel文件: