2015-12-21 68 views
0

我正在使用此腳本獲取大型csv文件,並通過第一列中的唯一值將其分開,然後保存新文件。我還想在每個文件的末尾添加3列,這些列包含基於前一列的計算結果。這些列也會有標題。我當前的代碼如下所示在python中將包含方程的列添加到csv文件中

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) 
+0

這哪裏是代碼嘗試添加3列,以及它具體是不是工作? –

+0

我沒有添加代碼來添加3列,因爲我無法弄清楚如何。從搜索有很多解釋如何添加行但不列。我所能做的就是通過獨特文本拼接原始文件 – Charlez

回答

0

如果您的意見是真實的,你很可能不喜歡這樣(爲虛列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) 
+0

我接收當我將該行添加到程序中時發生錯誤「KeyError:'col1' – Charlez

+0

當然。 'col1'只是一個組成。我不可能知道你的數據中有哪些列。 '我想在每個包含基於前面列的計算的文件末尾添加3列。 'col1'和'col2'應該是你以前的列,'*'是計算。 –

+1

哦,那真是愚蠢的我哈哈。謝謝。對於這一切我都很新穎。 – Charlez

相關問題