python读取一个文件夹中的所有csv文件为dataframe 并使用concat将这些dataframe拼接在一起
时间: 2024-05-02 17:17:17 浏览: 161
可以使用Python中的pandas库来实现读取一个文件夹中的所有csv文件为dataframe并使用concat将这些dataframe拼接在一起的操作。
首先,需要导入pandas库和os库:
``` python
import pandas as pd
import os
```
然后,可以使用os库的listdir函数来获取指定文件夹中的所有文件名,并使用pandas的read_csv函数来读取每个csv文件为dataframe,保存到一个列表中:
``` python
folder_path = 'path/to/folder'
csv_files = [f for f in os.listdir(folder_path) if f.endswith('.csv')]
dataframes = []
for file in csv_files:
file_path = os.path.join(folder_path, file)
df = pd.read_csv(file_path)
dataframes.append(df)
```
最后,可以使用pandas的concat函数将所有dataframe拼接在一起:
``` python
merged_df = pd.concat(dataframes, ignore_index=True)
```
其中,ignore_index参数可以用于重置所有行的索引号。
完整代码如下:
``` python
import pandas as pd
import os
folder_path = 'path/to/folder'
csv_files = [f for f in os.listdir(folder_path) if f.endswith('.csv')]
dataframes = []
for file in csv_files:
file_path = os.path.join(folder_path, file)
df = pd.read_csv(file_path)
dataframes.append(df)
merged_df = pd.concat(dataframes, ignore_index=True)
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)