MCPcopy Create free account
hub / github.com/dask/dask / _average

Function _average

dask/array/routines.py:2459–2509  ·  view source on GitHub ↗
(
    a, axis=None, weights=None, returned=False, is_masked=False, keepdims=False
)

Source from the content-addressed store, hash-verified

2457
2458
2459def _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)

Callers 2

averageFunction · 0.90
averageFunction · 0.85

Calls 8

asanyarrayFunction · 0.90
broadcast_toFunction · 0.90
getmaskarrayFunction · 0.90
result_typeFunction · 0.85
swapaxesMethod · 0.80
meanMethod · 0.45
sumMethod · 0.45
copyMethod · 0.45

Tested by

no test coverage detected