我最近刚刚开始学习csv模块。假设我们有这个 CSV 文件:
John,Jeff,Judy,
21,19,32,
178,182,169,
85,74,57,
我们想要读取此文件并创建一个包含名称(作为键)和每列总计(作为值)的字典。所以在这种情况下我们最终会得到:
d = {"John" : 284, "Jeff" : 275, "Judy" : 258}
所以我编写了这段代码,它显然运行良好,但我对此不满意,并且想知道是否有人知道更好或更有效/优雅的方法来做到这一点。因为那里的行太多了: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()
非常感谢您的回答:)
最佳答案
不确定你是否可以使用 pandas,但你可以按如下方式获取你的字典:
import pandas as pd
df = pd.read_csv('data.csv')
print(dict(df.sum()))
给予:
{'Jeff': 275, 'Judy': 258, 'John': 284}
关于Python:使用 csv 模块有效读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139744/