Mam prosty csv z dwiema kolumnami i muszę znaleźć średnią na klucz to znaczy wejście csv
A,2
B,3
A,1
C,2
B,2
D,4
C,2
wymagany wynik
{"A": 1.5, "B": 2.5, "C": 2, "D": 4}
Kod do tej pory:
pythoncsvfile = open("data.csv")
csv_reader = csv.reader(csvfile, delimiter=",")
for row in csv_reader:
print (row[0],row[1])
Odpowiedzi:
2 dla odpowiedzi № 1Opcja A
Za pomocą csv
import csv
import collections
out = collections.defaultdict(list)
with open("file.csv") as f:
for line in csv.reader(f):
out[line[0]].append(int(line[1]))
for k in out:
out[k] = sum(out[k]) / len(out[k])
print(dict(out))
{"A": 1.5, "B": 2.5, "C": 2.0, "D": 4.0}
Opcja B
Za pomocą pandas
import pandas as pd
df = pd.read_csv("file.csv", header=None, names=["Key", "Value"])
out = df.groupby("Key").mean()
print(out.Value.to_dict())
{"A": 1.5, "B": 2.5, "C": 2.0, "D": 4.0}
1 dla odpowiedzi nr 2
Myślę, że możesz użyć następującego fragmentu kodu:
import csv
from collections import OrderedDict
data = OrderedDict()
with open("data.csv", "rb") as csvfile:
content = csv.reader(csvfile, delimiter=",")
for index, value in content:
if ( not data.has_key(index) ):
#initialize
data[index] = {"times":1, "total":float(value)}
else:
#index already present
data[index] = {"times": data[index]["times"]+1, "total":data[index]["total"]+float(value)}
def average(data):
results = OrderedDict()
for index, values in data.iteritems():
results[index] = values["total"]/values["times"]
return results
print average(data)
OrderedDict([("A", 1.5), ("B", 2.5), ("C", 2.0), ("D", 4.0)])
HTH