Finding average of variable in objects python

numpy, python

Solution

import numpy as np
scores, ratings = np.array([(t.score, t.rating) for t in text_collection]).T

print 'average score: ', np.mean(scores)
print 'average rating: ', np.mean(ratings)
print 'average positive score: ', np.mean(scores[scores > 0])
print 'average negative score: ', np.mean(scores[scores < 0])

EDIT:

To check if there actually are any negative scores, you could so something like this:

if np.count_nonzero(scores < 0):
    print 'average negative score: ', np.mean(scores[scores < 0])

Problem

How can I iterate over a group of objects to find their mean in the most efficent way? This uses just one loop (except perhaps loops in Numpy) but I was wondering whether there was a better way. At the moment, I am doing this: ``` scores = [] ratings= [] negative_scores = [] positive_scores = [] for t in text_collection: scores.append(t.score) ratings.append(t.rating) if t.score < 0: negative_scores.append(t.score) elif t.score > 0: positive_scores.append(t.score) print "average score:", numpy.mean(scores) print "average rating:", numpy.mean(ratings) print "average negative score:", numpy.mean(negative_scores) print "average positive score:", numpy.mean(positive_scores) ``` Is there a better way of doing this?

Original source