我最近刚开始学习csv模块。假设我们有这个CSV文件:
John,Jeff,Judy,
21,19,32,
178,182,169,
85,74,57,
我们想阅读这个文件并创建一个字典,其中包含每个列的名称(作为键)和总计(作为值)。因此,在这种情况下,我们将得到:
^{pr2}$所以我写了这段代码,它显然运行得很好,但我并不满意,我想知道是否有人知道更好或更高效/优雅的方法来实现这一点。因为这里有太多的行:D(或者我们可以把它概括一点——也就是说,我们不知道有多少个字段)
d = {}
import csv
with open("file.csv") as f:
readObject = csv.reader(f)
totals0 = 0
totals1 = 0
totals2 = 0
totals3 = 0
currentRowTotal = 0
for row in readObject:
currentRowTotal += 1
if currentRowTotal == 1:
continue
totals0 += int(row[0])
totals1 += int(row[1])
totals2 += int(row[2])
if row[3] == "":
totals3 += 0
f.close()
with open(filename) as f:
readObject = csv.reader(f)
currentRow = 0
for row in readObject:
while currentRow <= 0:
d.update({row[0] : totals0})
d.update({row[1] : totals1})
d.update({row[2] : totals2})
d.update({row[3] : totals3})
currentRow += 1
return(d)
f.close()
非常感谢您的回答:)
最后一个操作栏是空的:
不确定你是否可以使用熊猫,但你可以得到你的口述如下:
给出:
^{pr2}$使用顶行来计算列标题是什么。根据标题初始化汇总字典。在
让我补充一下,您不必关闭
with
块之后的文件。with
的全部意义在于它负责关闭文件。在另外,请允许我指出,您发布的数据似乎有四列:
^{pr2}$所以我才这么做:
相关问题 更多 >
编程相关推荐