# A user implemented a Gini coefficient in Python

986    Asked by varshaChauhan in Data Science , Asked on Nov 9, 2019
Answered by varsha Chauhan

def gini(x):

# Mean absolute difference.

mad = np.abs(np.subtract.outer(x, x)).mean()

# Relative mean absolute difference

# Gini coefficient is half the relative mean absolute difference.

return 0.5 * rmad

How is it possible to adjust to take an array of weights as a second vector?

For example

gini([1, 2, 3]) # No weight: 0.22.

gini([1, 1, 1, 2, 2, 3]) # Manually weighted: 0.23.

gini([1, 2, 3], weight=[3, 2, 1]) # Should also give 0.23.

In such case the calculation of mad need to be replaced by the following code

x = np.array([1, 2, 3, 6])

c = np.array([2, 3, 1, 2])

count = np.multiply.outer(c, c)

mad = np.abs(np.subtract.outer(x, x) * count).sum() / count.sum()

np.mean(x)can be replaced by

np.average(x, weights=c)

Below is the full function

def gini(x, weights=None):

if weights is None:

weights = np.ones_like(x)

count = np.multiply.outer(weights, weights)

mad = np.abs(np.subtract.outer(x, x) * count).sum() / count.sum()

return 0.5 * rmad

For checking the result, gini2() uses Numpy.repeat() to repeat elements

def gini2(x, weights=None):

if weights is None:

weights = np.ones(x.shape[0], dtype=int)

x = np.repeat(x, weights)

mad = np.abs(np.subtract.outer(x, x)).mean()