我想将多头 DataFrame 保存为 Excel 文件。以下是示例代码:
import pandas as pd
import numpy as np
header = pd.MultiIndex.from_product([['location1','location2'],
['S1','S2','S3']],
names=['loc','S'])
df = pd.DataFrame(np.random.randn(5, 6),
index=['a','b','c','d','e'],
columns=header)
df.to_excel('result.xlsx')
excel文件中有两个问题,如下所示:问题 1:
标题下有一个空行。请让我知道如何避免 Pandas 在 Excel 文件中写入/插入空行。
问题 2:
我想保存没有索引的 DataFrame。但是,当我设置
index=False
,我收到以下错误: df.to_excel('result.xlsx', index=False)
错误:NotImplementedError: Writing to Excel with MultiIndex columns and no index ('index'=False) is not yet implemented.
最佳答案
您可以创建 2 个数据框 - 只有标题和默认标题,并使用 startrow
将两者写入同一张表中范围:
header = df.columns.to_frame(index=False)
header.loc[header['loc'].duplicated(), 'loc'] = ''
header = header.T
print (header)
0 1 2 3 4 5
loc location1 location2
S S1 S2 S3 S1 S2 S3
df1 = df.set_axis(range(len(df.columns)), axis=1)
print (df1)
0 1 2 3 4 5
a -1.603958 1.067986 0.474493 -0.352657 -2.198830 -2.028590
b -0.989817 -0.621200 0.010686 -0.248616 1.121244 0.727779
c -0.851071 -0.593429 -1.398475 0.281235 -0.261898 -0.568850
d 1.414492 -1.309289 -0.581249 -0.718679 -0.307876 0.535318
e -2.108857 -1.870788 1.079796 0.478511 0.613011 -0.441136
with pd.ExcelWriter('output.xlsx') as writer:
header.to_excel(writer, sheet_name='Sheet_name_1', header=False, index=False)
df1.to_excel(writer, sheet_name='Sheet_name_1', header=False, index=False, startrow=2)
关于excel - 将多标题 DataFrame 保存到 Excel 文件时如何避免写入空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70431125/