Compute a mean of an array group by unique values in python

Viewed 196

If I have an array

[0,0,0,0,0,0,1,1,2,2,2,2]

How can I compute the mean by each unique value in the array using numpy.mean().

I'd like to have [6/12, 2/12,4/12] not using count or len but only np.mean

I am just starting with Python.

4 Answers

How can I compute the mean by each unique value in the array using numpy.mean().

Using numpy.mean might not possible.

But to achieve that you can use numpy.bincount and len

import numpy as np

np.bincount(a)/len(a)
array([0.5       , 0.16666667, 0.33333333])

You make no sense when you say you can only use the np.mean function. You need something else, unless you want to implement these functions yourself, which makes no sense.

In fact, you don’t even really need np.mean at all, but instead, np.unique:

import numpy as np
a = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2])
unique, counts = np.unique(a, return_counts = True)
s = sum(counts)
means = [count / s for count, value in zip(counts, unique)]

EDIT:

Of course, you could just simplify this to:

np.unique(a, return_counts = True)[1]  / a.size

which was pointed out by another answerer.

Use Counter for counting unique values count as follows:

import numpy as np
from collections import Counter

a = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2])
output = np.array(list(Counter(a).values()))/a.size

output will be:

output : [0.5        0.33333333 0.16666667]

Since you want the mean of counts (and not the values themselves), you can use np.unique to get the counts. a is your array:

np.unique(a,return_counts=True)[1]/a.size

output:

[0.5        0.16666667 0.33333333]
Related