Home > Software design >  How to splice a dataframe into smaller tables and save each table to an excel sheet
How to splice a dataframe into smaller tables and save each table to an excel sheet

Time:12-14

Here is a table

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')

I would like to create 3 mini tables from this table and save each mini table as a sheet in 1 excel file. The first stage should contain columns age and eye, second, fortune & food and the third, job and kids.

This is what I've attempted, but it doesn't make much sense

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' )

CodePudding user response:

If you are looking to save each two columns into a separate sheet, try:

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
  • Related