DataFrame Data Output to Excel File

Asked 1 years ago, Updated 1 years ago, 231 views

We transferred the DataFrame type data obtained by Pandas to an excel file.
I expected five tables to be pasted every nine lines, but the result was that only the fifth table was pasted in the expected position.(Like the picture below)
Also, the table data is 6 rows and 6 columns of data.
I thought that every time I output DataFrame type data to an excel file, all cell information would be overwritten, so I tried another process, but it didn't work.
Which part of this code should I change to output the table as expected?

import pandas as pd

# COUNTER FOR ARRANGEMENT
count = 0

# scraping destination url
url='OOO'

# The variable data stores all the scraping destination tables, and the data type is dataframe.
data=pd.read_html(url,header=0)

# Fill in the specified excel file with the data retrieved on the web
For dind data:
    d.to_excel("AAA.xlsx", startrow=1+count*9, startcol=0)
    count = count +1

Enter a description of the image here

python pandas

2022-11-03 08:50

1 Answers

Every time I output DataFrame type data to an excel file, I think all cell information is overwritten.

Maybe that's what it looks like
Instead of naming a file every time in the loop, you should first name the file and use it in the loop.

(I can't try it because I don't have an environment, but like this)
You may want to remove mode="a" or if_sheet_exists="overlay" depending on file conditions

with pd.ExcelWriter("AAA.xlsx",
        mode = "a",
        engine="openpyxl",
        if_sheet_exists="overlay",
    ) as writer:
    for count, din enumerate (data):
        d.to_excel(writer, sheet_name="Sheet1", startrow=1+count*9)

Note: (pandas.pydata.org) pandas.ExcelWriter


2022-11-03 08:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.