CSV合并并向每个文件中的每列添加新行

时间:2017-03-27 19:57:05

标签: python csv pandas machine-learning pycharm

我有一堆文件和文件标准就像

TestAP300
TestBP300
TestCP300
...
TestHP30

例如:

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"

每个文件有10列4行。我想只在一个文件中合并文件,并为每列添加新行。

先谢谢

1 个答案:

答案 0 :(得分:0)

输入文件:

a.csv:

"-0.9148","-1.7609","0.8441","-3.0872"
"-2.4155","-0.7446","0.7238","-1.5506"

b.csv:

"-0.2695","0.2271","0.7103","-4.7732"
"-0.5421","-0.6235","0.2131","-3.3143"

<强>解决方案:

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)

<强>结果:

"-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"