Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to splice a dataframe into smaller tables and save each table to an excel sheet

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading