Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate multiple data frames in pd.read_html() when saving to excel using Python

I am attempting to save data from multiple tables brought in through pd.read_html(). If I print df, I can see it captured all the data, but when saving the data it is only saving the first table to excel. How do I separate out the tables so I can save each one to a separate sheet in excel (i.e. Quarterly Income Statement on sheet1, Annual Income Statement on sheet2, etc.). Below is my code. Any help is appreciated.

dfs = pd.read_html(https://www.google.com/finance?q=googl&fstype=ii, flavor='html5lib')

writer = pd.ExcelWriter(output.xlsx, engine='xlsxwriter')
for df in dfs:
    df.to_excel(writer, sheet_name='Sheet1')
    writer.save()
like image 658
gluc7 Avatar asked Sep 22 '26 20:09

gluc7


1 Answers

You can iterate on your list and flush them to a new sheet of the same workbook

import pandas as pd

dfs = pd.read_html('https://www.google.com/finance?q=googl&fstype=ii', flavor='html5lib')

# Create a Pandas Excel writer.
xlWriter = pd.ExcelWriter('myworkbook.xlsx', engine='xlsxwriter')

# Write each df to its own sheet
for i, df in enumerate(dfs):
    df.to_excel(xlWriter, sheet_name='Sheet{}'.format(i))

# Close the writer and output the Excel file (mandatory!)
xlWriter.save()
like image 196
Julien Marrec Avatar answered Sep 25 '26 10:09

Julien Marrec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!