在Python中,你可以使用`pandas`库来读取多个表格数据。以下是几种常见的方法:
方法1:使用`glob`模块读取多个CSV文件
import glob
import pandas as pd
获取文件夹路径
path_list = glob.glob('data/*.csv') 假设多个表格都在data文件夹下
读取每个表格
df_list = []
for path in path_list:
df = pd.read_csv(path)
df_list.append(df)
合并所有表格
df_all = pd.concat(df_list, axis=0, ignore_index=True)
方法2:使用`os`模块读取一个文件夹下的多个表格
import os
import pandas as pd
获取文件夹路径
folder_path = 'your/folder/path'
获取文件夹下的所有文件
files = os.listdir(folder_path)
筛选出Excel文件
excel_files = [file for file in files if file.endswith('.xlsx') or file.endswith('.xls')]
读取每个Excel文件中的工作表
df_dict = {}
for file in excel_files:
file_path = os.path.join(folder_path, file)
xls = pd.ExcelFile(file_path)
for sheet_name in xls.sheet_names:
df_dict[sheet_name] = xls.parse(sheet_name)
方法3:使用`pd.ExcelFile`对象读取Excel文件中的多个工作表
import pandas as pd
创建ExcelFile对象
file_path = 'your/excel/file.xlsx'
excel_file = pd.ExcelFile(file_path)
读取所有工作表
df_dict = {sheet_name: excel_file.parse(sheet_name) for sheet_name in excel_file.sheet_names}
方法4:使用`xlrd`库读取Excel文件
import xlrd
打开工作簿
workbook = xlrd.open_workbook('path_to_excel_file.xlsx')
选择第一个工作表
sheet = workbook.sheet_by_index(0)
读取数据
data = []
for row_idx in range(sheet.nrows):
row = sheet.row_values(row_idx)
data.append(row)
创建DataFrame
df = pd.DataFrame(data[1:], columns=data)
以上方法可以帮助你读取不同格式的表格数据,并将其整合到`pandas`的`DataFrame`中进行分析。请根据你的具体需求选择合适的方法