我有一个包含几张纸的Excel文件。我想遍历Excel文件的每个工作表,并为文件中的每个工作表创建一个DataFrame。另外,我希望将DataFrames命名为“ hfi_(工作表名称)”。到目前为止,这是我编写的for循环,但是由于语法错误而无法运行。你能帮我解决这个问题吗?
<?php
return array(
'dsn' => env('LARAVEL_SENTRY_DSN'),
// capture release as git sha
// 'release' => trim(exec('git log --pretty="%h" -n1 HEAD')),
// Capture bindings on SQL queries
'breadcrumbs.sql_bindings' => true,
// Capture default user context
'user_context' => true,
);
答案 0 :(得分:0)
我建议将这些数据帧存储到dict
d={"hfi" + sheet:pd.DataFrame(pd.read_excel("/Users/glosophy/Desktop/hfi/hfi_2016.xlsx", sheet_name=sheet)) for sheet in hfi_file}
然后,您可以使用.get
来访问数据
d.get('your dict key')
答案 1 :(得分:0)
您需要先导入Excel文件,然后按名称阅读每张工作表
multi_sheet_file = pd.ExcelFile("/Users/glosophy/Desktop/hfi/hfi_2016.xlsx")
# Gets the sheet names in the file
excel_sheet_names = multi_sheet_file.sheet_names
dict_of_sheets = {}
for sheet in excel_sheet_names:
dict_of_sheets["hfi" + sheet] = pd.read_excel(multi_sheet_file, sheetname=sheet')
答案 2 :(得分:0)
我在平局上显然很慢,但这是另一个答案:
import pandas as pd
# importing these so sessionInfo comes up for them
import openpyxl
import xlrd
file = 'output.xlsx'
df1 = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
df2 = pd.DataFrame({'sheet2-col1': [0, 1], 'sheet2-col2': [30, 40]})
writer = pd.ExcelWriter(file)
df1.to_excel(writer, 'Sheet1')
df2.to_excel(writer, 'Sheet2')
writer.save()
reader = pd.ExcelFile(file)
dict = {"hfi" + i : pd.read_excel(file, sheet_name=i) for i in reader.sheet_names}
print(dict)
#> {'hfiSheet1': col1 col2
#> 0 1 3
#> 1 2 4, 'hfiSheet2': sheet2-col1 sheet2-col2
#> 0 0 30
#> 1 1 40}
创建于2018-08-30
import reprexpy
print(reprexpy.SessionInfo())
#> Session info --------------------------------------------------------------------
#> Platform: Darwin-17.7.0-x86_64-i386-64bit (64-bit)
#> Python: 3.6
#> Date: 2018-08-30
#> Packages ------------------------------------------------------------------------
#> openpyxl==2.5.6
#> pandas==0.23.4
#> reprexpy==0.1.1
#> xlrd==1.1.0
答案 3 :(得分:0)
这是我与您分享的最简单方法:
# read the sheet file
import pandas as pd
sheets = pd.ExcelFile('sheet_filename.xlsx')
# save each sheet to a dataframe
df1 = pd.read_excel(sheets, 'Sheet1')
df2 = pd.read_excel(sheets, 'Sheet2')
希望这对您有所帮助!