简体   繁体   English

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

[英]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.

相关问题 Python:当一个键有多个值时,如何将字典写入csv文件,每个键是一个新行,但每个值是一个新列? - Python: How to write dictionary to csv file when one key has multiple values, each key is a new row, but each value is a new column? 将带有每列值的标题行添加到多个 CSV 文件 - Adding a header row with values for each column to multiple CSV files 合并 CSV 文件并为每个文件添加列 - Merging CSV Files & Add Column to Each Python 从多个 CSV 文件中读取数据并将每个文件添加到新列 - Python Reading data from multiple CSV files and adding each file to a new column 将相同的列表添加到新列中的pandas DataFrame中的每一行 - Adding the same list to each row in a pandas DataFrame in a new column 计算每一行的链接数,并将计数添加为新列 - Counting number of links for each row and adding the counts as a new column 合并熊猫中的一列 - 只保留一行包含所有值而不是每个 matc 的新行 - Merging one column in pandas - only keep one row with all values instead of new row for each matc CSV 文件中每个新行的自动递增 Id 值 - Auto-increment Id value on each new row in CSV file 将每一行转置为 python 中的一列(来自 csv 文件) - Transpose each row into a column in python (from a csv file) 读取每列的第一个元素,然后读取 csv 文件中的整行 - Reading first element of each column and then the entire row in csv file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM