自动加载并合并多个 Excel 工作表的数据
现在,您将通过实现一个 for 循环,自动从 Excel 文件 listings.xlsx 中的三个交易所工作表导入上市信息。您将完成以下步骤:
- 使用
pd.ExcelFile()对象的sheet_names属性获取工作表名称。 - 创建一个空列表。
- 编写一个 for 循环,遍历这些工作表名称,将对应工作表中的数据读入一个变量。需要的话,添加一个标识列。每次迭代都将该变量的内容追加到列表中。
- 将列表中的所有 DataFrame 进行纵向合并。
和往常一样,如需帮助,请参考本章之前的练习或查阅 pandas 文档。pandas 已以 pd 导入。
本练习是课程的一部分
在 Python 中导入与管理金融数据
练习说明
- 使用文件
listings.xlsx创建pd.ExcelFile()对象,并赋值给变量xls。 - 从
xls的.sheet_names属性中获取工作表名称,并赋值给exchanges。 - 创建一个空列表,并赋值给变量
listings。 - 使用以
exchange为迭代变量的 for 循环遍历exchanges。在每次迭代中:- 使用
pd.read_excel(),以xls为数据源,exchange作为sheet_name参数,'n/a'作为na_values以处理缺失值。将结果赋值给listing。 - 在
listing中创建名为'Exchange'的新列,取值为exchange(迭代变量)。 - 将得到的
listingDataFrame 追加到listings中。
- 使用
- 使用
pd.concat()将listings的内容合并,并赋值给listing_data。 - 使用
.info()查看listing_data的内容。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create the pd.ExcelFile() object
xls = ____
# Extract the sheet names from xls
exchanges = ____.____
# Create an empty list: listings
# Import the data
for exchange in exchanges:
listing = pd.____(____, sheet_name=____, na_values='n/a')
listing['Exchange'] = ____
listings.____(____)
# Concatenate the listings: listing_data
listing_data = pd.____(____)
# Inspect the results
listing_data.info()