/ / पायथन में एक सीएसवी से कुंजी द्वारा औसत ढूँढना - पायथन, सीएसवी, औसत

पाइथन में एक सीएसवी से कुंजी द्वारा औसत ढूँढना - पायथन, सीएसवी, औसत

मेरे पास एक साधारण 2 कॉलम सीएसवी है और औसत प्रति कुंजी खोजने की आवश्यकता है अर्थात। इनपुट सीएसवी

A,2
B,3
A,1
C,2
B,2
D,4
C,2

आवश्यक आउटपुट

{"A": 1.5, "B": 2.5, "C": 2, "D": 4}

इस प्रकार कोड अब तक:

pythoncsvfile = open("data.csv")
csv_reader = csv.reader(csvfile, delimiter=",")
for row in csv_reader:
print (row[0],row[1])

उत्तर:

जवाब के लिए 2 № 1

विकल्प ए

का उपयोग करते हुए 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}

विकल्प बी

का उपयोग करते हुए 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}

उत्तर № 2 के लिए 1

मुझे लगता है कि आप कोड के निम्नलिखित भाग का उपयोग कर सकते हैं:

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