Skip to content Skip to sidebar Skip to footer

Weighted Gini Coefficient In Python

Here's a simple implementation of the Gini coefficient in Python, from https://stackoverflow.com/a/39513799/1840471: def gini(x): # Mean absolute difference. mad = np.abs(n

Solution 1:

the calculation of mad can be replaced by:

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)

Here is the full function:

defgini(x, weights=None):
    if weights isNone:
        weights = np.ones_like(x)
    count = np.multiply.outer(weights, weights)
    mad = np.abs(np.subtract.outer(x, x) * count).sum() / count.sum()
    rmad = mad / np.average(x, weights=weights)
    return0.5 * rmad

to check the result, gini2() use numpy.repeat() to repeat elements:

defgini2(x, weights=None):
    if weights isNone:
        weights = np.ones(x.shape[0], dtype=int)    
    x = np.repeat(x, weights)
    mad = np.abs(np.subtract.outer(x, x)).mean()
    rmad = mad / np.mean(x)
    return0.5 * rmad

Post a Comment for "Weighted Gini Coefficient In Python"