如何使用Python将新列附加到CSV文件? [英] How to append a new column to a CSV file using Python?

查看:76
本文介绍了如何使用Python将新列附加到CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在数组中存储了一组四个数字,我想将它们添加到得分"列下的CSV文件中.

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

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?

推荐答案

可能最简单的解决方案是使用 Pandas .虽然有些过分,但是对于CSV操作而言,它通常要干净得多,而CSV操作超出了直接读取/写入的范围.

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.

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

Say I have a CSV file as follows:

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')

这将添加一个新列,扩展性好,并且易于使用.生成的CSV文件将如下所示:

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

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

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

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

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)

这篇关于如何使用Python将新列附加到CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆