[英]CSV merging and adding new row to each column in each file
I have bunch of files and file standard goes like 我有一堆文件,文件标准如下
TestAP300
TestBP300
TestCP300
...
TestHP30
For Example: 例如:
Data A:
"-0.9148","-1.7609","0.8441","-3.0872"
"-2.4155","-0.7446","0.7238","-1.5506"
Data B:
"-0.2695","0.2271","0.7103","-4.7732"
"-0.5421","-0.6235","0.2131","-3.3143"
I would like to create file below :
"-0.9148","-1.7609","0.8441","-3.0872","A"
"-2.4155","-0.7446","0.7238","-1.5506","A"
"-0.2695","0.2271","0.7103","-4.7732","B"
"-0.5421","-0.6235","0.2131","-3.3143","B"
Each files has 10 columns and 4 rows. 每个文件有10列和4行。 I would like to merge files in only one file and adding new row to each column.
我只想合并一个文件中的文件,然后将新行添加到每一列。
Thanks in Advance 提前致谢
Input files: 输入文件:
a.csv: a.csv:
"-0.9148","-1.7609","0.8441","-3.0872"
"-2.4155","-0.7446","0.7238","-1.5506"
b.csv: b.csv:
"-0.2695","0.2271","0.7103","-4.7732"
"-0.5421","-0.6235","0.2131","-3.3143"
Solution: 解:
import os
import glob
import csv
import pandas as pd
files = glob.glob(r'D:\temp\.data\43055344\*.csv')
pd.concat(
[pd.read_csv(files[0], header=None).assign(f=os.path.basename(os.path.splitext(f)[0]))
for f in files
],
ignore_index=True
).to_csv(r'd:/temp/out.csv', header=None, index=False, quoting=csv.QUOTE_ALL)
Result: 结果:
"-0.9148","-1.7609","0.8441","-3.0872","a"
"-2.4155","-0.7446","0.7238","-1.5506","a"
"-0.9148","-1.7609","0.8441","-3.0872","b"
"-2.4155","-0.7446","0.7238","-1.5506","b"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.