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
(data, *, n=4, method='exclusive')
| 1173 | # external packages can be used for anything more advanced. |
| 1174 | |
| 1175 | def quantiles(data, *, n=4, method='exclusive'): |
| 1176 | """Divide *data* into *n* continuous intervals with equal probability. |
| 1177 | |
| 1178 | Returns a list of (n - 1) cut points separating the intervals. |
| 1179 | |
| 1180 | Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. |
| 1181 | Set *n* to 100 for percentiles which gives the 99 cuts points that |
| 1182 | separate *data* in to 100 equal sized groups. |
| 1183 | |
| 1184 | The *data* can be any iterable containing sample. |
| 1185 | The cut points are linearly interpolated between data points. |
| 1186 | |
| 1187 | If *method* is set to *inclusive*, *data* is treated as population |
| 1188 | data. The minimum value is treated as the 0th percentile and the |
| 1189 | maximum value is treated as the 100th percentile. |
| 1190 | |
| 1191 | """ |
| 1192 | if n < 1: |
| 1193 | raise StatisticsError('n must be at least 1') |
| 1194 | |
| 1195 | data = sorted(data) |
| 1196 | |
| 1197 | ld = len(data) |
| 1198 | if ld < 2: |
| 1199 | if ld == 1: |
| 1200 | return data * (n - 1) |
| 1201 | raise StatisticsError('must have at least one data point') |
| 1202 | |
| 1203 | if method == 'inclusive': |
| 1204 | m = ld - 1 |
| 1205 | result = [] |
| 1206 | for i in range(1, n): |
| 1207 | j, delta = divmod(i * m, n) |
| 1208 | interpolated = (data[j] * (n - delta) + data[j + 1] * delta) / n |
| 1209 | result.append(interpolated) |
| 1210 | return result |
| 1211 | |
| 1212 | if method == 'exclusive': |
| 1213 | m = ld + 1 |
| 1214 | result = [] |
| 1215 | for i in range(1, n): |
| 1216 | j = i * m // n # rescale i to m/n |
| 1217 | j = 1 if j < 1 else ld-1 if j > ld-1 else j # clamp to 1 .. ld-1 |
| 1218 | delta = i*m - j*n # exact integer math |
| 1219 | interpolated = (data[j - 1] * (n - delta) + data[j] * delta) / n |
| 1220 | result.append(interpolated) |
| 1221 | return result |
| 1222 | |
| 1223 | raise ValueError(f'Unknown method: {method!r}') |
| 1224 | |
| 1225 | |
| 1226 | ## Normal Distribution ##################################################### |
searching dependent graphs…