ratings = np.array([[1, 4, 5, 0], [2, 0, 3, 0], [4, 0, 0, 0]], dtype=np.float)

def get_means(ratings):
    ratings[np.where(ratings == 0)] = np.nan
user_means = np.nanmean(ratings, axis=1)
movie_means = np.nanmean(ratings, axis=0)
return {'user_means': user_means, 'movie_means': movie_means}
An efficient way to calculate the mean of each column or row of non-zero elements