在单独的csv列中写入dictionary的值并创建头

2024-05-23 21:15:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个字典,它使用日期作为键,并为每个日期添加了多个值。字典是通过读取原始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中写入值,并在每行之间跳过一行。在

我希望每个值都写在自己的列中,并且希望每个列都有这样的标题:

^{pr2}$

Tags: csvthedate字典mypricedictfile
2条回答

我建议用熊猫。在

如果将数据设置为字典列表,其中每个字典表示一行,而字典的键是值为行值的列,则执行此操作时:

import pandas as pd
pd.DataFrame(list_of_dictionaries).to_csv('put_your_filename_here.csv')

您应该正确格式化数据。在

items()返回键、值的列表,这不是您要写入文件的内容。此代码起作用:

with open('mycsvfile.csv', 'w') as f:
    w = csv.writer(f)
    w.writerow(['DATE', 'Volume', 'Notional Value', 'SEC FEES', 'Clearing Fees', 'Total Fees'])
    for date in sorted(my_dict):
        w.writerow([date] + my_dict[date])

如果不希望输出排序,只需删除sorted()函数。在

相关问题 更多 >