我有一个带有这样的行的文件
id, car_type, cost
1, benz, 60000
2, benz, 55000
3, bmw, 30000
4, benz, 25000
5, bmw, 26000
6, ford, 5000
我想按每个car_type
的总费用对该文件进行排序。例如,“ benz
”的总费用为60000 + 55000 + 25000 = 14000
所以最终输出应该是
benz, 140000
bmw, 56000
ford, 5000
到目前为止,这就是我所拥有的:
file = "small_sample.txt"
f=open(file,"r")
lines=f.readlines()[1:]
car_and_cost ={}
for x in lines:
cost = x.split(',')[4].rstrip('\n')
car_and_cost.update({x.split(',')[3]:float(cost)})
f.close()
print(car_and_cost)
new_dic = {}
for key,lis in car_and_cost.items():
new_dic[key] = sum(lis)
print(new_dic)
我几乎陷入困境。首先,我从中生成的字典的总和不正确,而且我根本不知道如何按值对字典进行排序
答案 0 :(得分:3)
这是使用csv
和collections
模块的一种方法
例如:
import csv
from collections import defaultdict, OrderedDict
result = defaultdict(int)
with open(filename) as infile:
reader = csv.DictReader(infile)
for row in reader: #Iterate Each row
result[row[" car_type"]] += int(row[" cost"]) #Add costs
print(OrderedDict(sorted(result.items(), key=lambda x: x[1], reverse=True)))
输出:
OrderedDict([(' benz', 140000), (' bmw', 56000), (' ford', 5000)])
答案 1 :(得分:1)
使用熊猫:
import pandas as pd
df = pd.read_csv(logFile)
result = df.groupby(' car_type').sum()
print(result)
输出:
id cost
car_type
benz 7 140000
bmw 8 56000
ford 6 5000
编辑:
logFile = "tem.csv"
array = []
import csv
with open("tem.csv", "r+") as fin:
for row in csv.reader(fin):
array.append(row[1:])
dd = {k: 0 for k in dict(array).keys()}
for x in array: dd[x[0]] += int(x[1])
print(dd)
输出:
{' benz': 140000, ' bmw': 56000, ' ford': 5000}
或者如果您希望它们在列表中:
print([[k,v] for k,v in dd.items()])
输出:
[[' benz', 140000], [' bmw', 56000], [' ford', 5000]]