pandas可以非常方便的寫數據到excel,那么如何寫多個dataframe到不同的sheet呢?
使用pandas.ExcelWriter
import pandas as pd writer = pd.ExcelFile('your_path.xlsx') df1 = pd.DataFrame()df2 = pd.DataFrame() df1.to_excel(writer, sheet_name='df_1')df2.to_excel(writer, sheet_name='df_2') writer.save()網上的大部分答案基本上都是這些內容,但是這里有個大坑,你會發現找不到想要的xlsx文件。
那么問題出在哪?
我們看看ExcelWriter源碼就知道了
class ExcelFile(object): """ Class for parsing tabular excel sheets into DataFrame objects. Uses xlrd. See read_excel for more documentation Parameters ---------- io : string, path object (pathlib.Path or py._path.local.LocalPath), file-like object or xlrd workbook If a string or path object, expected to be a path to xls or xlsx file engine: string, default None If io is not a buffer or path, this must be set to identify io. Acceptable values are None or xlrd """
這里已經說的很清楚了,希望傳入的是excel的路徑,你只傳了個文件名,當然找不到了。
而且從這里我們可以看到,pandas.ExcelWriter實質上是用xlrd來解析excel的。這個wrapper提供了更簡單的接口。
以上這篇pandas分別寫入excel的不同sheet方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答