如何使用 Python 将新列附加到 CSV 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36882130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:29:33  来源:igfitidea点击:

How to append a new column to a CSV file using Python?

pythoncsv

提问by Akhil Kintali

I have stored a set of four numbers in an array which I want to add to a CSV file under the 'Score' column.

我在一个数组中存储了一组四个数字,我想将其添加到“分数”列下的 CSV 文件中。

with open('Player.csv', 'ab') as csvfile:
    fieldnames = ['Score']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for i in range(0, l):
       writer.writerow({'Score': score[i]})

It appends to the file, but this adds a new row instead of a new column. Could someone guide into appending it into a new column?

它附加到文件中,但这会添加一个新行而不是新列。有人可以指导将其附加到新列中吗?

回答by Alexander Huszagh

Probably the simplest solution would be to use Pandas. It's overkill, but it generally is much cleaner for CSV manipulation that extends beyond straight reading/writing.

可能最简单的解决方案是使用Pandas。这有点矫枉过正,但对于超出直接读取/写入范围的 CSV 操作来说,它通常要干净得多。

Say I have a CSV file as follows:

假设我有一个 CSV 文件,如下所示:

ASSETNUM    ASSETTAG    ASSETTYPE   AUTOWOGEN
cent45  9164        0
cent45  9164        0

Then, the relevant code to add a column would be as follows:

然后,添加列的相关代码如下:

import pandas as pd

df = pd.read_csv('path/to/csv.csv', delimiter='\t')
# this line creates a new column, which is a Pandas series.
new_column = df['AUTOWOGEN'] + 1
# we then add the series to the dataframe, which holds our parsed CSV file
df['NewColumn'] = new_column
# save the dataframe to CSV
df.to_csv('path/to/file.csv', sep='\t')

This adds a new column, scales well, and is easy to use. The resulting CSV file then would look as follows:

这增加了一个新列,缩放良好,并且易于使用。生成的 CSV 文件如下所示:

    ASSETNUM    ASSETTAG    ASSETTYPE   AUTOWOGEN   NewColumn
0   cent45  9164        0   1
1   cent45  9164        0   1

Compare this to the CSV module code for the same purpose (modified from here):

将此与出于相同目的的 CSV 模块代码进行比较(从此处修改):

with open('path/to/csv.csv', 'r') as fin:
    reader = csv.reader(fin, delimiter='\t')
    with open('new_'+csvfile, 'w') as fout:
        writer = csv.writer(fout, delimiter='\t')
        # set headers here, grabbing headers from reader first
        writer.writerow(next(reader) + ['NewColumn']

        for row in reader:
            # use whatever index for the value, or however you want to construct your new value
            new_value = reader[-1] + 1
            row.append(new_value)
            writer.writerow(row)