首页 > 解决方案 > 使用 concat 合并不同目录中的多个 csv 文件

问题描述

我一直在使用这篇文章来合并不同目录中具有相同名称的 csv。

这是我的 csv 文件的示例

csv A(dir1)

距离,x_u,y_u,u_comp

0,0,.01,.001

1,1,.01,.004

2,2,.03,.002

等等

csv A(dir2)

距离,x_v,y_v,v_comp

0,0,.01,5

1,1,.01,5.2

2,2,.03,4.98

等等

我想要获得的是这样的csv:

距离,x_u,y_u,u_comp,x_v,y_v,v_comp

0,0,.01,.001,0,.01,5

1,1,.01,.004,1,.01,5.2

2,2,.03,.002,2,.03,4.98

基本上,我试图通过距离值加入 csvs。

这是我正在使用的代码:

import glob
import pandas as pd

CONCAT_DIR = "/FILES_CONCAT/"

# Use glob module to return all csv files under root directory. Create DF from this.
files = pd.DataFrame([file for file in glob.glob("root/*/*")], columns=["fullpath"])

#    fullpath
# 0  root\dir1\A.csv
# 1  root\dir1\B.csv
# 2  root\dir2\A.csv
# 3  root\dir2\B.csv

# Split the full path into directory and filename
files_split = files['fullpath'].str.rsplit("/", 1, expand=True).rename(columns={0: 'path', 1:'filename'})

#    path       filename
# 0  root\dir1  A.csv
# 1  root\dir1  B.csv
# 2  root\dir2  A.csv
# 3  root\dir2  B.csv

# Join these into one DataFrame
files = files.join(files_split)

#    fullpath         path       filename
# 0  root\dir1\A.csv  root\dir1   A.csv
# 1  root\dir1\B.csv  root\dir1   B.csv
# 2  root\dir2\A.csv  root\dir2   A.csv
# 3  root\dir2\B.csv  root\dir2   B.csv

# Iterate over unique filenames; read CSVs, concat DFs, save file
for f in files['filename'].unique():
    paths = files[files['filename'] == f]['fullpath'] # Get list of fullpaths from unique filenames
    dfs = [pd.read_csv(path, header=None) for path in paths] # Get list of dataframes from CSV file paths
    concat_df = pd.concat(dfs) # Concat dataframes into one
    concat_df.to_csv(CONCAT_DIR + f) # Save dataframe
    

当我运行它时,我得到了这个:

距离,x_u,y_u,u_comp

0,0,.01,.001

1,1,.01,.004

2,2,.03,.002

......

距离,x_v,y_v,v_comp

0,0,.01,5

1,1,.01,5.2

2,2,.03,4.98

我相信它与 concat_df = pd.concat(dfs) 行有关,但我不确定要更改什么。我在这里查看了其他示例,但其中大多数不涉及循环,我不确定是否使其工作。

提前致谢!

标签: python-3.x

解决方案


推荐阅读