doc*_*rer 5 python dictionary list pandas
我有一个字典dictData,它是从csv文件的3列(0,3和4)创建的,其中每个键都是一个日期时间对象,每个值都是一个列表,包含两个数字(让我们称它们为a和b,所以列表是[a,b])存储为字符串:
import csv
import datetime as dt
with open(fileInput,'r') as inFile:
csv_in = csv.reader(inFile)
dictData = {(dt.datetime.strptime(rows[0],'%d/%m/%Y %H:%M')):[rows[3],rows[4]] for rows in csv_in}
Run Code Online (Sandbox Code Playgroud)
我想做两件事:首先,我想对整个字典中的每个值求和(即对所有值进行求和,然后对所有b值求和).如果它是单值的字典,我会做这样的事情:
total = sum((float(x) for x in dictData.values()))
Run Code Online (Sandbox Code Playgroud)
如何更改此项以便.values标识列表中的第一个(或第二个)项目?(即a或b值)
我想计算列表中第一项的所有零值.
dictData = {'2010': ['1', '2'],
'2011': ['4', '3'],
'2012': ['0', '45'],
'2013': ['8', '7'],
'2014': ['9', '0'],
'2015': ['22', '1'],
'2016': ['3', '4'],
'2017': ['0', '5'],
'2018': ['7', '8'],
'2019': ['0', '9'],
}
print 'sum of 1st items = %d' % sum([float(v[0]) for v in dictData.values()])
print 'sum of 2nd items = %d' % sum([float(v[1]) for v in dictData.values()])
print 'count of zeros = %d' % sum([(float(v[0]) == 0) for v in dictData.values()])
sum of 1st items = 54
sum of 2nd items = 84
count of zeros = 3
Run Code Online (Sandbox Code Playgroud)