(
a, axis=None, weights=None, returned=False, is_masked=False, keepdims=False
)
| 2457 | |
| 2458 | |
| 2459 | def _average( |
| 2460 | a, axis=None, weights=None, returned=False, is_masked=False, keepdims=False |
| 2461 | ): |
| 2462 | # This was minimally modified from numpy.average |
| 2463 | # See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt |
| 2464 | # or NUMPY_LICENSE.txt within this directory |
| 2465 | # Wrapper used by da.average or da.ma.average. |
| 2466 | a = asanyarray(a) |
| 2467 | |
| 2468 | if weights is None: |
| 2469 | avg = a.mean(axis, keepdims=keepdims) |
| 2470 | scl = avg.dtype.type(a.size / avg.size) |
| 2471 | else: |
| 2472 | wgt = asanyarray(weights) |
| 2473 | |
| 2474 | if issubclass(a.dtype.type, (np.integer, np.bool_)): |
| 2475 | result_dtype = result_type(a.dtype, wgt.dtype, "f8") |
| 2476 | else: |
| 2477 | result_dtype = result_type(a.dtype, wgt.dtype) |
| 2478 | |
| 2479 | # Sanity checks |
| 2480 | if a.shape != wgt.shape: |
| 2481 | if axis is None: |
| 2482 | raise TypeError( |
| 2483 | "Axis must be specified when shapes of a and weights differ." |
| 2484 | ) |
| 2485 | if wgt.ndim != 1: |
| 2486 | raise TypeError( |
| 2487 | "1D weights expected when shapes of a and weights differ." |
| 2488 | ) |
| 2489 | if wgt.shape[0] != a.shape[axis]: |
| 2490 | raise ValueError( |
| 2491 | "Length of weights not compatible with specified axis." |
| 2492 | ) |
| 2493 | |
| 2494 | # setup wgt to broadcast along axis |
| 2495 | wgt = broadcast_to(wgt, (a.ndim - 1) * (1,) + wgt.shape) |
| 2496 | wgt = wgt.swapaxes(-1, axis) |
| 2497 | if is_masked: |
| 2498 | from dask.array.ma import getmaskarray |
| 2499 | |
| 2500 | wgt = wgt * (~getmaskarray(a)) |
| 2501 | scl = wgt.sum(axis=axis, dtype=result_dtype, keepdims=keepdims) |
| 2502 | avg = multiply(a, wgt, dtype=result_dtype).sum(axis, keepdims=keepdims) / scl |
| 2503 | |
| 2504 | if returned: |
| 2505 | if scl.shape != avg.shape: |
| 2506 | scl = broadcast_to(scl, avg.shape).copy() |
| 2507 | return avg, scl |
| 2508 | else: |
| 2509 | return avg |
| 2510 | |
| 2511 | |
| 2512 | @derived_from(np) |
no test coverage detected