Calculate the Gini coefficient of a numpy array.
(array)
| 1 | import numpy as np |
| 2 | |
| 3 | def gini(array): |
| 4 | """Calculate the Gini coefficient of a numpy array.""" |
| 5 | # based on bottom eq: |
| 6 | # http://www.statsdirect.com/help/generatedimages/equations/equation154.svg |
| 7 | # from: |
| 8 | # http://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm |
| 9 | # All values are treated equally, arrays must be 1d: |
| 10 | array = array.flatten() |
| 11 | if np.amin(array) < 0: |
| 12 | # Values cannot be negative: |
| 13 | array -= np.amin(array) |
| 14 | # Values cannot be 0: |
| 15 | array += 0.0000001 |
| 16 | # Values must be sorted: |
| 17 | array = np.sort(array) |
| 18 | # Index per array element: |
| 19 | index = np.arange(1,array.shape[0]+1) |
| 20 | # Number of array elements: |
| 21 | n = array.shape[0] |
| 22 | # Gini coefficient: |
| 23 | return ((np.sum((2 * index - n - 1) * array)) / (n * np.sum(array))) |