简体   繁体   中英

how to save a pandas DataFrame to an excel file?

I am trying to load data from the web source and save it as a Excel file but not sure how to do it. What should I do?

import requests
import pandas as pd
import xmltodict


url = "https://www.kstan.ua/sitemap.xml"
res = requests.get(url)
raw = xmltodict.parse(res.text)

data = [[r["loc"], r["lastmod"]] for r in raw["urlset"]["url"]]
print("Number of sitemaps:", len(data))
df = pd.DataFrame(data, columns=["links", "lastmod"])
df.to_csv("output.csv", index=False)

或者

df.to_excel("output.xlsx")

You can write the dataframe to excel using the pandas ExcelWriter , such as this:

import pandas as pd
with pd.ExcelWriter('path_to_file.xlsx') as writer:
    dataframe.to_excel(writer)

If you want to create multiple sheets in the same file

with pd.ExcelWriter('csv_s/results.xlsx') as writer:
   same_res.to_excel(writer, sheet_name='same')
   diff_res.to_excel(writer, sheet_name='sheet2')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM