python-3.x - 使用 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 - Python遍历001-100范围内的文件名
- pug - 除了将值作为参数传入之外,有没有办法将值公开给 pug 模板?
- android - 使用导航组件将一个片段的值传递给另一个片段时未生成 FragmentArgs 类
- android - 有没有办法访问 BottomNavigationBarItem() 的标签文本并更新 appBarTitle 值,而不是使用硬编码的 SWITCH - CASE?
- flutter - 将 ViewModel 的访问方法 Flutter 到另一个 ViewModel 中
- c++ - 如何重载 + 运算符来添加两个队列?
- html - 我必须申请什么CSS来摆脱这个无用的间距?
- deep-learning - LSTM 进化预测
- arm - 如何写入 DE1-SOC 板 HPS 部分的 USB OTG 控制器寄存器?
- java - RecyclerView 中的搜索过滤器不显示任何内容