【发布时间】:2014-12-26 13:25:18
【问题描述】:
我创建了一个使用日期作为键的字典,并为每个日期添加了多个值。通过读取原始 csv 来填充字典,以便我可以创建每个日期的总数。
我的代码:
import csv
##Opens the csv file to be read
tradedata=open("test.csv","r")
##Reads the csv file
tradedatareader = csv.reader(tradedata,delimiter=',',quotechar='"')
##create dictionary
my_dict = {}
for row in tradedatareader:
Date = row[1][0:8]
volume = int(row[4])
price = float(row[5])
Transtype=row[6]
##Find SEC_Fee
if Transtype !="BUY":
ttype =1
else:
ttype=0
secfee=(ttype*volume*price*.0000221)
##Finds Notional Value
notional_val = (volume*price)
##Finds Clearing Fees
cl_fee = (volume*.0005)
if cl_fee < .05:
clearing_fee = 0.05
else:
clearing_fee = (volume*.0005)
##Finds Totals per Date
my_dict[Date] = my_dict.setdefault(Date, [0,0,0,0,0])
my_dict[Date][0] = my_dict[Date][0] + volume
my_dict[Date][1] = my_dict[Date][1] + notional_val
my_dict[Date][2] = my_dict[Date][2] + secfee
my_dict[Date][3] = my_dict[Date][3] + clearing_fee
my_dict[Date][4] = my_dict[Date][4] + secfee + clearing_fee
## Writes totals to CSV
with open('mycsvfile.csv','w') as f:
w = csv.writer(f, delimiter = ',')
w.writerows(my_dict.items())
目前这会将键写入 A 列,将值写入 B 列,并在每行之间跳过一行。
我希望每个值都写在自己的列中,并且希望每个列都有这样的标题:
DATE Volume Notional Value SEC FEES Clearing Fees Total Fees
20140612 2751 157750.56 3.4132565999 1.4500000 4.8632566
20140612 5148 270200.02 5.831338266 2.692499999 8.523838265999998
【问题讨论】:
-
我不确定你的帖子为什么被否决,但我会投赞成票,因为我认为它很有价值。
-
另一方面,我建议将变量命名为小写,并在它们之间使用下划线。示例:
Date应变为date。这将使您的代码可读 w.r.t. Pythonic 约定。 -
我猜反对票是因为这里的代码比解决问题所必需的要多得多。同意,不过是一个有用的问题。
-
我是 Python 的新手,周一刚开始为我分配的项目查看它。非常感谢您的鼓励。
标签: python csv dictionary