如何将数据帧拼接成更小的表格,并将每个表格保存到excel表格中



这是一个表

df = {'index':['Larry','Moe','Curly'],
'age':[54,58,65],
'eye':['blue','brown','brown'],
'fortune':[1,1.5,1.2],
'food':['pizza','pasta','burgers'],
'job':['actor','actor','actor'],
'kids':[2,3,4]}
df = pd.DataFrame(df)
df = df.set_index('index')

我想从这个表中创建3个迷你表,并将每个迷你表保存为1个excel文件中的工作表。第一个阶段应该包含列age和eye,第二个,fortune&食物和第三,工作和孩子。

这是我尝试过的,但没有多大意义

col = df.columns
with pd.Excelwriter('filename' + '.xlsx') as xlswriter:
for col in df:
col = col[::2]
df.to_excel(xlswriter, index=False, sheet_name = 'sheet' )

如果您希望将每两列保存到一个单独的工作表中,请尝试:

col = df.columns
# ExcelWriter not Excelwriter
with pd.ExcelWriter('filename' + '.xlsx') as xlswriter:
for i in range(0,len(col), 2):
# you can use `iloc` to slice by column number
df.iloc[:,i:i+2].to_excel(xlswriter, index=False,      # are you sure you want to remove the index?
sheet_name = f'sheet {i}' )  # change sheet name so you don't override your data

最新更新