python - 使用 Python 将列添加到现有的 CSV 文件

标签 python python-2.7 csv import

我正在尝试使用 python 向现有的 csv 文件添加新的列标题和值。我查找的所有内容都将标题附加到最后一列的最后一行。这就是我希望我的结果本质上是什么。
Header Header2 Header3 NewHeader Value Value2 Value3 NewValue
我目前得到的是:

Header   Header2   Header3
Value    Value2    Value3**NewHeader
NewValue`

这是我的代码:
import csv
  with open('filename.csv', 'a') as csvfile:
  fieldnames = ['pageviewid']
  writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

  writer.writeheader()
  writer.writerow({'pageviewid': 'Baked'})
  writer.writerow({'pageviewid': 'Lovely'})
  writer.writerow({'pageviewid': 'Wonderful'})

最佳答案

如果使用 Pandas 是一种选择:

import pandas as pd
df = pd.read_csv('filename.csv')
new_column = pd.DataFrame({'new_header': ['new_value_1', 'new_value_2', 'new_value_3']})
df = df.merge(new_column, left_index = True, right_index = True)
df.to_csv('filename.csv', index = False)

关于python - 使用 Python 将列添加到现有的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40229469/

相关文章:

python - 从 CSV 中写入/读取特殊字符(Python 3.6)

python - 迭代 QTreeView 行

python - $、^ 和 * 符号在 python 2.7 和 BS4 中的作用

python - 将正则表达式模式作为系统参数传递给 Python 脚本

python-2.7 - lxml - 无法替换 child 的 child

Python CSV 到 HTML 表代码不起作用

python - 获取 pandas 中每列的最大值数量

python - 模块 'fft' 中无名称 'scipy'

python - 如何pickle sklearn Pipeline 中的各个步骤?

mysql - CSV 数据未插入相应的 MySQL 表中