如何在 Python 中打开 Excel 文件? [英] How can I open an Excel file in Python?
问题描述
如何打开 Excel 文件以便在 Python 中读取?
我已经使用读取命令打开了文本文件,例如 sometextfile.txt
.如何为 Excel 文件执行此操作?
在较新版本的 Pandas 中,您可以将工作表名称作为参数传递.
file_name = # 文件路径 + 文件名sheet = # 工作表名称或工作表编号或工作表编号和名称列表将熊猫导入为 pddf = pd.read_excel(io=file_name, sheet_name=sheet)print(df.head(5)) # 打印数据帧的前 5 行
查看文档以获取有关如何传递 sheet_name
的示例:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html
旧版本:
您也可以使用 pandas
包....>
当您处理包含多个工作表的 Excel 文件时,您可以使用:
将pandas导入为pdxl = pd.ExcelFile(路径 + 文件名)xl.sheet_names>>>[u'Sheet1', u'Sheet2', u'Sheet3']df = xl.parse("Sheet1")df.head()
df.head()
将打印 Excel 文件的前 5 行
如果您使用单个工作表处理 Excel 文件,您可以简单地使用:
将pandas导入为pddf = pd.read_excel(路径+文件名)打印 df.head()
How do I open a file that is an Excel file for reading in Python?
I've opened text files, for example, sometextfile.txt
with the reading command. How do I do that for an Excel file?
Edit:
In the newer version of pandas, you can pass the sheet name as a parameter.
file_name = # path to file + file name
sheet = # sheet name or sheet number or list of sheet numbers and names
import pandas as pd
df = pd.read_excel(io=file_name, sheet_name=sheet)
print(df.head(5)) # print first 5 rows of the dataframe
Check the docs for examples on how to pass sheet_name
:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html
Old version:
you can use pandas
package as well....
When you are working with an excel file with multiple sheets, you can use:
import pandas as pd
xl = pd.ExcelFile(path + filename)
xl.sheet_names
>>> [u'Sheet1', u'Sheet2', u'Sheet3']
df = xl.parse("Sheet1")
df.head()
df.head()
will print first 5 rows of your Excel file
If you're working with an Excel file with a single sheet, you can simply use:
import pandas as pd
df = pd.read_excel(path + filename)
print df.head()
这篇关于如何在 Python 中打开 Excel 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!