在不同的数据框中从excel读取多个选项卡 [英] reading multiple tabs from excel in different dataframes

查看:56
本文介绍了在不同的数据框中从excel读取多个选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将电子表格中的多个标签读取到不同的数据框,并且一旦所有包含数据的标签结束,程序都应停止.

I am trying to read multiple tabs in spreadsheet to different dataframes and once all tabs with data are over the program should stop.

第一部分,我希望做类似的事情

For first part I am looking to do something like

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

我希望程序在读取所有带有数据的标签后停止运行

I want the program to stop once all tabs with data are read

推荐答案

演示:

文件名

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']

我们可以使用它来循环浏览工作表

we can use it for looping through sheets

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

一种更优雅的方法是生成DataFrames字典:

a bit more elegant way is to generate a dictionary of DataFrames:

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

这篇关于在不同的数据框中从excel读取多个选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆