Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save a pandas DataFrame to an excel file?

Tags:

python

pandas

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"])
like image 466
Игорь Avatar asked Mar 14 '19 19:03

Игорь


People also ask

Can you save a pandas DataFrame to file?

In this article, we will learn how we can export a Pandas DataFrame to a CSV file by using the Pandas to_csv() method. By default, the to csv() method exports DataFrame to a CSV file with row index as the first column and comma as the delimiter.

Can pandas export to excel?

You can write any data (lists, strings, numbers etc) to Excel, by first converting it into a Pandas DataFrame and then writing the DataFrame to Excel. To export a Pandas DataFrame as an Excel file (extension: . xlsx, . xls), use the to_excel() method.

How do I save a DataFrame as an XLSX?

Algorithm: Create the DataFrame. Determine the name of the Excel file. Call to_excel() function with the file name to export the DataFrame.

How do I export Panda DataFrame?

Exporting the DataFrame into a CSV filePandas DataFrame to_csv() function exports the DataFrame to CSV format. If a file argument is provided, the output will be the CSV file. Otherwise, the return value is a CSV format like string. sep: Specify a custom delimiter for the CSV output, the default is a comma.


2 Answers

df.to_csv("output.csv", index=False)

OR

df.to_excel("output.xlsx")
like image 107
mujjiga Avatar answered Sep 23 '22 06:09

mujjiga


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)
like image 21
razimbres Avatar answered Sep 23 '22 06:09

razimbres