如何将工作表转换为Pandas中的数据框?

时间:2017-07-25 18:12:09

标签: python excel python-3.x pandas

我正在尝试使用Pandas从Python工作簿中读取不同的工作表。当我阅读整个工作簿然后我想应用.merge()然后读取第一个工作表,但不考虑其他工作表。我试着阅读工作簿的每个工作表,但我猜他们没有成功转换为数据框,因为当我申请.merge()时,我最终得到以下错误:ValueError: Invalid file path or buffer object type: <class 'pandas.core.frame.DataFrame'>

这是我到目前为止所做的:

此代码适用于将整个工作簿转换为数据框,但仅处理第一个工作表的数据

import pandas as pd
import pypyodbc

#sql extractor
start_date = date.today()
retrieve_values = "[DEV].[CS].[QT_KPIExport] @start_date='{start_date:%Y-%m-%d}'".format(
    start_date=start_date)
connection = pypyodbc.connect(driver="{SQL Server}", server="xxx.xxx.xxx.xxx", uid="X",pwd="xxx", Trusted_Connection="No")
data_frame_sql = pd.read_sql(retrieve_values, connection)

#Read the entire workbook 
wb_data = pd.ExcelFile("C:\\Users\\Dev\\Testing\\Daily_Data\\NSN-Daily Data Report.xlsx")
#Convert to a dataframe the entire workbook
data_frame_excel = pd.read_excel(wb_data,index_col=None,na_values=['NA'],parse_cols="J")

#apply merge
merged_df   = data_frame_sql.merge(data_frame_excel,how="inner",on="sectorname")

此代码尝试读取不同的工作表并将它们转换为数据框但尚未成功...... (查看下面的答案)

data_frame_sql = pd.read_sql(retrieve_values, connection)

#Method 1: Tried to parse worksheet 2
#Read the entire workbook and select the specific worksheet
wb_data = pd.ExcelFile("C:\\Users\\Dev\\Testing\\Daily_Data\\NSN-Daily Data Report.xlsx", sheetname="Sheet-2")
data_frame_excel = pd.read_excel(wb_data,index_col=None,na_values=['NA'],parse_cols="J")

#apply merge
merged_df   = data_frame_sql.merge(data_frame_excel,how="inner",on="sectorname")
#No success... the data of the first sheet is read

#Method 2: Tried to parse worksheet 2
#Read the entire workbook
wb_data = pd.ExcelFile("C:\\Users\\Dev\\Testing\\Daily_Data\\NSN-Daily Data Report.xlsx")
data_frame_excel = pd.read_excel(wb_data,index_col=None,na_values=['NA'],parse_cols="J")

#select one specific sheet
ws_sheet_2 = wb_data.parse("Sheet-2")

#apply merge
merged_df   = data_frame_sql.merge(ws_sheet_2,how="inner",on="sectorname")
# No success.... ValueError: Invalid file path or buffer object type: <class 'pandas.core.frame.DataFrame'>

非常感谢任何帮助或建议。

2 个答案:

答案 0 :(得分:1)

通过使用带有read_excel方法的sheetname = None参数,可以将工作簿中的所有工作表都放到字典中。键/值对将是名称/数据帧。

ws_dict = pd.read_excel('excel_file.xlsx', sheetname=None)

请注意,在将来的pandas版本中,sheetname参数将更改为sheet_name ...

答案 1 :(得分:0)

我找到了解决问题的方法。

#Method 1: Add the sheetname once you have read the entire workbook 
#Read the entire workbook 
wb_data = pd.ExcelFile("C:\\Users\\Dev\\Testing\\Daily_Data\\NSN-Daily Data 
Report.xlsx")
#Select your sheetname to read 
data_frame_excel = pd.read_excel(wb_data,index_col=None,na_values=
['NA'],parse_cols="J" sheetname="Sheet-2")

#apply merge
merged_df   = 
data_frame_sql.merge(data_frame_excel,how="inner",on="sectorname")