使用pandas在Python中读取Excel文件

我想这样读取一个excel文件:

newFile = pd.ExcelFile(PATH\FileName.xlsx) ParsedData = pd.io.parsers.ExcelFile.parse(newFile) 

它会抛出一个错误,说两个参数的预期,我不知道第二个参数是什么,也是我想在这里实现的是将Excel文件转换为DataFrame,我是否正确的做法? 还是有没有其他的方式来做到这一点使用pandas?

closures:首先调用ExcelFile ,然后调用.parse方法并将表名传递给它。

 >>> xl = pd.ExcelFile("dummydata.xlsx") >>> xl.sheet_names [u'Sheet1', u'Sheet2', u'Sheet3'] >>> df = xl.parse("Sheet1") >>> df.head() Tid dummy1 dummy2 dummy3 dummy4 dummy5 \ 0 2006-09-01 00:00:00 0 5.894611 0.605211 3.842871 8.265307 1 2006-09-01 01:00:00 0 5.712107 0.605211 3.416617 8.301360 2 2006-09-01 02:00:00 0 5.105300 0.605211 3.090865 8.335395 3 2006-09-01 03:00:00 0 4.098209 0.605211 3.198452 8.170187 4 2006-09-01 04:00:00 0 3.338196 0.605211 2.970015 7.765058 dummy6 dummy7 dummy8 dummy9 0 0.623354 0 2.579108 2.681728 1 0.554211 0 7.210000 3.028614 2 0.567841 0 6.940000 3.644147 3 0.581470 0 6.630000 4.016155 4 0.595100 0 6.350000 3.974442 

你正在做的是调用生活在类本身上的方法,而不是实例,这是可以的(虽然不是非常习惯的),但是如果你这样做,你还需要传递表名:

 >>> parsed = pd.io.parsers.ExcelFile.parse(xl, "Sheet1") >>> parsed.columns Index([u'Tid', u'dummy1', u'dummy2', u'dummy3', u'dummy4', u'dummy5', u'dummy6', u'dummy7', u'dummy8', u'dummy9'], dtype=object) 

这是非常简单和容易的方法。

 import pandas df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1') # or using sheet index starting 0 df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2) 

查看文档详细信息http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.read_excel.html

以为我应该在这里添加,如果你想访问行或列循环通过他们,你这样做:

 import pandas as pd # open the file xlsx = pd.ExcelFile(PATH\FileName.xlsx) # get the first sheet as an object sheet1 = xlsx.parse(0) # get the first column as a list you can loop through # where the is 0 in the code below change to the row or column number you want column = sheet1.icol(0).real # get the first row as a list you can loop through row = sheet1.irow(0).real 

我认为这应该满足你的需要:

 import pandas as pd # Read the excel sheet to pandas dataframe DataFrame = pd.read_excel("PATH\FileName.xlsx", sheetname=0)