Divide *data* into *n* continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. Set *n* to 100 for percentiles which gives the 99 cuts points that separate
(data, *, n=4, method='exclusive')
| 771 | # external packages can be used for anything more advanced. |
| 772 | |
| 773 | def quantiles(data, *, n=4, method='exclusive'): |
| 774 | """Divide *data* into *n* continuous intervals with equal probability. |
| 775 | |
| 776 | Returns a list of (n - 1) cut points separating the intervals. |
| 777 | |
| 778 | Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. |
| 779 | Set *n* to 100 for percentiles which gives the 99 cuts points that |
| 780 | separate *data* in to 100 equal sized groups. |
| 781 | |
| 782 | The *data* can be any iterable containing sample. |
| 783 | The cut points are linearly interpolated between data points. |
| 784 | |
| 785 | If *method* is set to *inclusive*, *data* is treated as population |
| 786 | data. The minimum value is treated as the 0th percentile and the |
| 787 | maximum value is treated as the 100th percentile. |
| 788 | """ |
| 789 | if n < 1: |
| 790 | raise StatisticsError('n must be at least 1') |
| 791 | data = sorted(data) |
| 792 | ld = len(data) |
| 793 | if ld < 2: |
| 794 | raise StatisticsError('must have at least two data points') |
| 795 | if method == 'inclusive': |
| 796 | m = ld - 1 |
| 797 | result = [] |
| 798 | for i in range(1, n): |
| 799 | j, delta = divmod(i * m, n) |
| 800 | interpolated = (data[j] * (n - delta) + data[j + 1] * delta) / n |
| 801 | result.append(interpolated) |
| 802 | return result |
| 803 | if method == 'exclusive': |
| 804 | m = ld + 1 |
| 805 | result = [] |
| 806 | for i in range(1, n): |
| 807 | j = i * m // n # rescale i to m/n |
| 808 | j = 1 if j < 1 else ld-1 if j > ld-1 else j # clamp to 1 .. ld-1 |
| 809 | delta = i*m - j*n # exact integer math |
| 810 | interpolated = (data[j - 1] * (n - delta) + data[j] * delta) / n |
| 811 | result.append(interpolated) |
| 812 | return result |
| 813 | raise ValueError(f'Unknown method: {method!r}') |
| 814 | |
| 815 | |
| 816 | # === Measures of spread === |
nothing calls this directly
no test coverage detected