Python pandas.read_excel 参数“sheet_name”不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47975866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:27:48  来源:igfitidea点击:

pandas.read_excel parameter "sheet_name" not working

pythonexcelpandas

提问by user7065687

According to the doc, pandas.read_excelhas a parameter sheet_namethat allows specifying which sheet is read. But when I am trying to read the second sheet from an excel file, no matter how I set the parameter (sheet_name = 1, sheet_name = 'Sheet2'), the dataframe always shows the first sheet, and passing a list of indices (sheet_name = [0, 1]) does not return a dictionary of dataframes but still the first sheet. What might be the problem here?

根据docpandas.read_excel有一个参数sheet_name可以指定读取哪个工作表。但是,当我尝试从 excel 文件中读取第二张工作表时,无论我如何设置参数 ( sheet_name = 1, sheet_name = 'Sheet2'),数据框始终显示第一张工作表,并且传递索引列表 ( sheet_name = [0, 1]) 不会返回数据框字典,但是仍然是第一张。这里可能有什么问题?

回答by Sergey Solod

It looks like you're using the old version of Python. So try to change your code

看起来您使用的是旧版本的 Python。所以尝试改变你的代码

df = pd.read_excel(file_with_data, sheetname=sheet_with_data)

It should work properly.

它应该可以正常工作。

回答by pyhazard

You can try to use pd.ExcelFile:

您可以尝试使用pd.ExcelFile

xls = pd.ExcelFile('path_to_file.xls')
df1 = pd.read_excel(xls, 'Sheet1')
df2 = pd.read_excel(xls, 'Sheet2')

回答by Torolito

This works:

这有效:

df = pd.read_excel(open(file_path_name), 'rb'), sheetname = sheet_name)

file_path_name = your file
sheet_name = your sheet name

This does not for me:

这不适合我:

df = pd.read_excel(open(file_path_name), 'rb'), sheet_name = sheet_name)

Gave me only the first sheet, no matter how I defined sheet_name.

无论我如何定义 sheet_name,都只给了我第一张表。

--> it is an known error: https://github.com/pandas-dev/pandas/issues/17107

--> 这是一个已知错误:https: //github.com/pandas-dev/pandas/issues/17107

回答by Lee Li Fong

Try at Terminal, type the following first, then re-run your program: pip install xlrd

在终端尝试,首先输入以下内容,然后重新运行您的程序:pip install xlrd