简体   繁体   English

Python CSV,使用CSV将多列合并为一列

[英]Python CSV, Combining multiple columns into one column using CSV

I've been trying to figure out a way to combine all the columns in a csv I have into one columns.我一直在尝试找出一种方法来将 csv 中的所有列组合成一个列。

import csv
with open('test.csv') as f:
    reader = csv.reader(f)
    with open('output.csv', 'w') as g:
        writer = csv.writer(g)
        for row in reader:
            new_row = [' '.join([row[0], row[1]])] + row[2:]
            writer.writerow(new_row)

This worked to combine the first two columns, but I've been having trouble trying to loop it and get the rest of the columns into just one.这可以组合前两列,但我一直无法尝试将其循环并将列的 rest 合并为一个列。

You should just pass row to .join because it's an array.您应该将row传递给.join因为它是一个数组。

import csv
with open('test.csv') as f:
    reader = csv.reader(f)
    with open('output.csv', 'w') as g:
        writer = csv.writer(g)
        for row in reader:
            new_row = [' '.join(row)] # <---- CHANGED HERE
            writer.writerow(new_row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM