[英]Reading values from Excel workbook in every worksheet in particular column
[英]Import every worksheet in an excel workbook and save to a dataframe named by the worksheet name
我有一个带有 3 个工作表的 excel 工作簿,它们分别称为“Z_scores”、“Alpha”和“Rho”。
将来,随着模型的数量及其相应的参数存储在此处,此工作簿将增加。
在我的 function 中,我希望单独导入每个工作表并将其保存到 dataframe,dataframe 的名称应由工作表的名称决定。
到目前为止,我有这个 function 但我无法动态命名 dataframe 我不确定应该在返回语句中写什么
仅供参考:导入标识符 function 只是一种扫描工作表名称的方式,不应插入带有标识符的名称,例如,在工作表名称的开头放置一个空格将阻止导入工作表。
#import libraries
import pandas as pd
#define function
def import_excel(filename, import_identifier):
#Create dataframe of the excel
df = pd.read_excel('Excel.xlsx')
# this will read the first sheet into df
xls = pd.ExcelFile('Excel.xlsx')
#Delete all worksheet that begin with the import_identifier
worksheets = []
for x in all_worksheets:
if x[0] != import_identifier:
worksheets.append(x)
#Loop through the sheets which are flagged for importing and import each
#sheet individually into a dataframe
for sheetname in worksheets:
#Encase the sheetname in quotation marks to satisfy the sheetname function in read_excel
sheetname_macro_str = '"{}"'.format(sheetname_macro)
#Import the workbook and save to dynamically named dataframe
sheetname_macro = pd.read_excel(xls, sheetname=sheetname_macro_str)
#What would I return here, how do I ensure the data frames are stored?
#return
正如您在此线程中所读到的,DataFrame object 不能可靠地“命名”。 通常,分配了 object 的 Python 变量将描述或区分它。
如果您希望在代码中存储对多个 DataFrame 的引用,您可能需要为此创建一个列表、元组或字典(在导入函数的 scope 之外)。 如果您使用字典,则可以使用工作表名称作为键:
dataframes = {}
dataframes[friendly_sheetname] = dataframe_from_sheet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.