[英]How to Save or export multiple dataframes in excel in different tabs?
[英]reading multiple tabs from excel in different dataframes
我正在嘗試將電子表格中的多個選項卡讀取到不同的數據框,一旦所有帶有數據的選項卡都結束程序應該停止。
對於第一部分,我希望做一些類似的事情
xls = pd.ExcelFile('Unique.xlsx')
for i in range(1,n): # n should be number of tabs with data
try:
df_Sector(i)=xls.parse('Sheet'+i) # df_Sector(i) has to be dataframe
except:
pass
我希望程序在讀取所有帶有數據的選項卡后停止
演示:
文檔名稱
In [94]: fn = r'D:\temp\.data\test.xlsx'
創建pandas.io.excel.ExcelFile
對象
In [95]: xl = pd.ExcelFile(fn)
它有sheet_names
屬性
In [96]: xl.sheet_names
Out[96]: ['Sheet1', 'aaa']
我們可以用它來循環工作表
In [98]: for sh in xl.sheet_names:
...: df = xl.parse(sh)
...: print('Processing: [{}] ...'.format(sh))
...: print(df.head())
...:
Processing: [Sheet1] ...
col1 col2 col3
0 11 12 13
1 21 22 23
2 31 32 33
Processing: [aaa] ...
a b c
0 1 2 3
1 4 5 6
2 7 8 9
一種更優雅的方法是生成一個 DataFrame 字典:
In [100]: dfs = {sh:xl.parse(sh) for sh in xl.sheet_names}
In [101]: dfs.keys()
Out[101]: dict_keys(['Sheet1', 'aaa'])
In [102]: dfs['Sheet1']
Out[102]:
col1 col2 col3
0 11 12 13
1 21 22 23
2 31 32 33
In [103]: dfs['aaa']
Out[103]:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
這將讀取所有工作表並制作數據框字典:
xl = pd.read_excel('Unique.xlsx', sheet_name=None)
要獲取特定的工作表,您可以執行以下操作:
xl_dict = {}
sheetname_list = ['blah1', 'blah2', 'blah3']
for sheet in sheetname_list:
xl_dict[sheet] = pd.read_excel('Unique.xlsx', sheet_name=sheet)
或者:
xl = pd.read_excel('Unique.xlsx', sheet_name=sheetname_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.