pandas读取多个excel文件,代码
时间: 2023-09-24 15:11:02 浏览: 273
你可以使用`pandas`库中的`read_excel()`函数来读取多个Excel文件,具体代码如下:
```python
import pandas as pd
import glob
# 获取所有要读取的Excel文件路径
excel_files = glob.glob('path/to/files/*.xlsx')
# 循环读取每个Excel文件,并将它们合并成一个数据框
dfs = []
for file in excel_files:
df = pd.read_excel(file)
dfs.append(df)
merged_df = pd.concat(dfs, ignore_index=True)
```
在上面的代码中,`glob.glob()`函数用于获取指定路径下的所有Excel文件路径。`pd.read_excel()`函数用于读取每个Excel文件,并将它们存储在一个数据框列表中。最后,`pd.concat()`函数用于将这些数据框合并成一个数据框。`ignore_index=True`参数用于重新设置合并后的数据框的索引。
相关问题
读取多个excel文件代码
在Python中,如果你需要同时读取多个Excel文件,可以使用pandas库的`read_excel()`函数的迭代功能。下面是一个基本的例子,展示了如何读取目录下的所有Excel文件:
```python
import os
import pandas as pd
def read_excel_files(directory):
# 获取指定目录下所有的Excel文件
excel_files = [f for f in os.listdir(directory) if f.endswith('.xls') or f.endswith('.xlsx')]
dfs = []
for file_name in excel_files:
# 构建完整的文件路径
file_path = os.path.join(directory, file_name)
# 读取单个Excel文件
df = pd.read_excel(file_path)
# 将每个DataFrame添加到列表中
dfs.append(df)
# 合并所有DataFrame(默认采用水平堆叠)
combined_df = pd.concat(dfs, ignore_index=True)
return combined_df
# 使用函数
directory = 'your_directory' # 替换为你存放Excel文件的实际路径
all_data = read_excel_files(directory)
# 现在'all_data'包含了所有文件的数据
```
在这个例子中,我们遍历指定目录下的所有以`.xls`或`.xlsx`结尾的文件,然后将它们逐个读入到pandas DataFrame中。如果想按照特定方式合并(如按行拼接),可以调整`pd.concat()`的参数。
pandas可以读取多个excel文件吗
是的,pandas可以读取多个Excel文件。你可以使用Python的os模块来获取文件夹中的所有Excel文件,然后使用pandas中的read_excel()函数逐个读取。以下是一个示例代码:
```python
import os
import pandas as pd
path = '/path/to/folder/containing/excel/files'
files = os.listdir(path)
excels = [file for file in files if file.endswith('.xlsx')]
dfs = []
for excel in excels:
df = pd.read_excel(os.path.join(path, excel))
dfs.append(df)
# 合并数据
result = pd.concat(dfs)
```
在这个例子中,我们首先使用os.listdir()函数获取文件夹中的所有文件,然后使用列表推导式将列表筛选为以.xlsx结尾的Excel文件。接下来,我们使用for循环逐个读取Excel文件,并将它们存储在一个列表中。最后,我们使用pd.concat()函数将所有DataFrame合并为一个DataFrame。
阅读全文
相关推荐
















