Return the weighted average of array over the given axis. Parameters ---------- a : array_like Data to be averaged. Masked entries are not taken into account in the computation. axis : int, optional Axis along which to average `a`. If None, averaging is
(a, axis=None, weights=None, returned=False, *,
keepdims=np._NoValue)
| 525 | |
| 526 | |
| 527 | def average(a, axis=None, weights=None, returned=False, *, |
| 528 | keepdims=np._NoValue): |
| 529 | """ |
| 530 | Return the weighted average of array over the given axis. |
| 531 | |
| 532 | Parameters |
| 533 | ---------- |
| 534 | a : array_like |
| 535 | Data to be averaged. |
| 536 | Masked entries are not taken into account in the computation. |
| 537 | axis : int, optional |
| 538 | Axis along which to average `a`. If None, averaging is done over |
| 539 | the flattened array. |
| 540 | weights : array_like, optional |
| 541 | The importance that each element has in the computation of the average. |
| 542 | The weights array can either be 1-D (in which case its length must be |
| 543 | the size of `a` along the given axis) or of the same shape as `a`. |
| 544 | If ``weights=None``, then all data in `a` are assumed to have a |
| 545 | weight equal to one. The 1-D calculation is:: |
| 546 | |
| 547 | avg = sum(a * weights) / sum(weights) |
| 548 | |
| 549 | The only constraint on `weights` is that `sum(weights)` must not be 0. |
| 550 | returned : bool, optional |
| 551 | Flag indicating whether a tuple ``(result, sum of weights)`` |
| 552 | should be returned as output (True), or just the result (False). |
| 553 | Default is False. |
| 554 | keepdims : bool, optional |
| 555 | If this is set to True, the axes which are reduced are left |
| 556 | in the result as dimensions with size one. With this option, |
| 557 | the result will broadcast correctly against the original `a`. |
| 558 | *Note:* `keepdims` will not work with instances of `numpy.matrix` |
| 559 | or other classes whose methods do not support `keepdims`. |
| 560 | |
| 561 | .. versionadded:: 1.23.0 |
| 562 | |
| 563 | Returns |
| 564 | ------- |
| 565 | average, [sum_of_weights] : (tuple of) scalar or MaskedArray |
| 566 | The average along the specified axis. When returned is `True`, |
| 567 | return a tuple with the average as the first element and the sum |
| 568 | of the weights as the second element. The return type is `np.float64` |
| 569 | if `a` is of integer type and floats smaller than `float64`, or the |
| 570 | input data-type, otherwise. If returned, `sum_of_weights` is always |
| 571 | `float64`. |
| 572 | |
| 573 | Examples |
| 574 | -------- |
| 575 | >>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True]) |
| 576 | >>> np.ma.average(a, weights=[3, 1, 0, 0]) |
| 577 | 1.25 |
| 578 | |
| 579 | >>> x = np.ma.arange(6.).reshape(3, 2) |
| 580 | >>> x |
| 581 | masked_array( |
| 582 | data=[[0., 1.], |
| 583 | [2., 3.], |
| 584 | [4., 5.]], |