2015-06-18 175 views
5

我需要一個CSV文件看起來像這樣...寫作CSV輸出蟒蛇

Name,Price1,Price2,Date1,Date2 
ABC,1000,7500,5/1,6/1 
DEF,3000,500,5/1,7/1 
GHI,5000,3500,6/1,8/1 

並寫入到另一個csv文件,使它看起來像這樣...

Name,May,June,July,August 
ABC,7500,1000, , 
DEF,500, ,3000 
GHI, ,3500, ,5000 

的空間猜想,因爲沒有到那裏是空白的,這是我到目前爲止的代碼

import csv 

with open('test-data.csv','rb') as f: 
    csv_file=csv.reader(f) 
    data=[row for row in csv_file] 

    with open('csv-out.csv', 'wb') as out: 
     writer=csv.writer(out) 
     writer.writerow(['Name','May','June','July','August']) 
     for row in data: 
      writer.writerow(row[0]) 

我是新來的蟒蛇,我ñ不確定如何使用CVS模塊。我正在考慮製作一個數組,並將這些數字匹配到幾個月。由於price1與date2一起使用,price2與date1一起使用。我只是在想這個嗎?我正在四處搜尋,也可能使用日期時間將月份號碼連接到月份名稱。任何幫助或指導表示讚賞!再次感謝!

編輯:

難道是很難,如果我想也是從一列類似

Name,May,June,July,August 
ABC,7500,1000, , 
DEF,500, ,3000 
GHI, ,3500, ,5000  
Total,8000,4500,3000,5000 

回答

2

像這樣的東西應該爲你的問題的工作:

import csv 
import calendar 
from collections import defaultdict 

months = [calendar.month_name[i] for i in range(0, 13)] 
totals = defaultdict(int) 

with open("data.csv", "r") as inf, open("data-out.csv", "w") as ouf: 
    reader = csv.DictReader(inf) 
    writer = csv.DictWriter(ouf, ['Name'] + months[5:9]) 
    writer.writeheader() 
    for row in reader: 
     m1 = months[int(row['Date1'].split('/')[0])] 
     p2 = int(row['Price2']) 
     totals[m1] += p2 

     m2 = months[int(row['Date2'].split('/')[0])] 
     p1 = int(row['Price1']) 
     totals[m2] += p1 

     writer.writerow({'Name': row['Name'], m1: p2, m2: p1}) 

    totals['Name'] = 'Total' 
    writer.writerow(totals) 

with open("data-out.csv", "r") as f: 
    print(f.read()) 

Name,May,June,July,August 
ABC,7500,1000,, 
DEF,500,,3000, 
GHI,,3500,,5000 
Total,8000,4500,3000,5000 

如果您Date#的跨越整個一年您可以更改:

writer = csv.DictWriter(ouf, ['Name'] + months[5:9]) 

writer = csv.DictWriter(ouf, ['Name'] + months[1:]) 
+0

爲什麼我得到這個錯誤:回溯(最近通話最後一個): 文件 「waterfall.py」,13號線,在 M1 =月[INT(行['日期1 '] .split('/')[0])] KeyError:'Date1' – Captain4725

+0

nvm我再次感謝它! – Captain4725

1

添加一些數字從什麼樣子,你想要做一個列移位。對於一些圖書館來說這實際上很難,但是下面的圖書館應該是相當有幫助的。

Pandas Python