【问题标题】:Adding columns that contain equations to a csv file in python在python中将包含方程式的列添加到csv文件
【发布时间】:2015-12-21 22:12:46
【问题描述】:

我正在使用这个脚本来获取一个大的 csv 文件,并在第一列中用唯一值分隔它,然后保存新文件。我还想在每个文件的末尾添加 3 列,其中包含基于前列的计算。这些列也将具有标题。我目前的代码如下

import csv, itertools as it, operator as op

csv_contents = []
with open('Nov15.csv', 'rb') as fin:
  file_reader = csv.DictReader(fin)   # default delimiter is comma
  print file_reader
  fieldnames = file_reader.fieldnames # save for writing
  for line in file_reader:            # read in all of your data
    csv_contents.append(line)         # gather data into a list (of dicts)

# input to itertools.groupby must be sorted by the grouping value 
sorted_csv_contents = sorted(csv_contents, key=op.itemgetter('Object'))

for groupkey, groupdata in it.groupby(sorted_csv_contents, key=op.itemgetter('Object')):
    with open('slice_{:s}.csv'.format(groupkey), 'wb') as gips:
        file_writer = csv.DictWriter(gips, fieldnames=fieldnames)
        file_writer.writeheader()         
        file_writer.writerows(groupdata)

【问题讨论】:

  • 这段代码在哪里尝试添加 3 列,具体是如何不工作的?
  • 我没有添加代码来添加 3 列,因为我不知道怎么做。通过搜索,有很多关于如何添加行而不是列的解释。我所能做的就是通过独特的文本拼接原始文件

标签: python csv export-to-csv


【解决方案1】:

如果您的 cmets 为真,您可能会这样做(对于虚列 col1col2 和计算 col1 * col2

for line in file_reader:  # read in all of your data
    line['calculated_col0'] = line['col1'] * line['col2']
    csv_contents.append(line)  # gather data into a list (of dicts)

【讨论】:

  • 当我将该行添加到程序 "KeyError: 'col1' 时收到一个错误
  • 当然。 col1 只是编造的。我不可能知道您的数据中有哪些列。 I would like to also add 3 columns at the end of each file that contain calculations based on the previous columnscol1col2 应该是你以前的列,* 是计算。
  • 哦,那是我的愚蠢哈哈。谢谢你。我对这一切都很陌生。
  • 如果您收到问题的解决方案,通常最好接受适当的答案,这样其他人就可以看到您不再需要帮助。这使 Stackoverflow 保持整洁干净,并奖励您选择其答案作为解决方案的人一些虚构的 Internet 积分!
猜你喜欢
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多