Python Forum

Full Version: [Solved] df.to_excel: certain rows
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I would like to write only a few rows from a dataframe into an Excel file.
Is this possible directly when writing or do I have to define a new variable first?


import pandas as pd
import numpy as np

d = {'col1': [1,2,3,4,5,6], 'col2': [1,2,3,4,5,6]}
df = pd.DataFrame(data=d)
df

with pd.ExcelWriter('minimal_to_excel.xlsx') as writer:  
    df.to_excel(writer, startrow=1, sheet_name='row_1_to_3')
One way is to feed .to_excel with filtered dataframe. For first three rows it would be:

df.iloc[:3].to_excel(writer, startrow=1, sheet_name='row_1_to_3')  
(May-26-2021, 06:21 AM)perfringo Wrote: [ -> ]One way is to feed .to_excel with filtered dataframe. For first three rows it would be:

df.iloc[:3].to_excel(writer, startrow=1, sheet_name='row_1_to_3')  

Thank you!