python - 在单独的 csv 列中写入字典的值并创建标题

标签 python csv dictionary

我创建了一个字典,它使用日期作为键,并向每个日期添加多个值。该字典是通过读取原始 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

最佳答案

我建议使用 Pandas。

如果您将数据设置为字典列表,其中每个字典代表一行,字典的键是列,值是行值,那么当您这样做时:

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

您的数据格式应该正确。

关于python - 在单独的 csv 列中写入字典的值并创建标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26654100/

相关文章:

javascript - 从输入类型文件选择的 CSV 文件生成数组

python - 优化 Python CSV 阅读器性能

python-3.x - 将 DataFrame 附加到 {Key : Empty DataFrame (with columns)} 中的空 DataFrame

VBA 字典,需要类 424 对象错误

python - sleep /暂停/休眠 Windows PC

python - Tensorflow - tf.nn.conv2D() 中的权重值是否发生变化?

python - python中sqlite3的executemany语句的限制

regex - 使用 REGEX 匹配单词的 BASH 脚本

python - AttributeError : 'str' object has no attribute 'decode' in fitting Logistic Regression Model

c# - 如何检查字典中的所有值在 C# 中是否相同?