[英]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.我正在尝试从 web 源加载数据并将其保存为 Excel 文件,但不确定如何操作。 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 use DataFrame.to_excel(). 您可以使用DataFrame.to_excel()。 See detailed in https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html
请参阅https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html中的详细信息
You can write the dataframe to excel using the pandas ExcelWriter , such as this:您可以使用 pandas ExcelWriter将数据框写入 excel,例如:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.