Skip to content

Instantly share code, notes, and snippets.

@Nodd
Created January 27, 2015 10:42
Show Gist options
  • Save Nodd/926e3e21af1f04741c14 to your computer and use it in GitHub Desktop.
Save Nodd/926e3e21af1f04741c14 to your computer and use it in GitHub Desktop.
numpy.average timing
Timer unit: 1e-06 s
Total time: 0.211221 s
File: /usr/lib/python3.4/site-packages/numpy/lib/function_base.py
Function: average at line 436
Line # Hits Time Per Hit % Time Line Contents
==============================================================
436 @profile
437 def average(a, axis=None, weights=None, returned=False):
438 """
439 Compute the weighted average along the specified axis.
440
441 Parameters
442 ----------
443 a : array_like
444 Array containing data to be averaged. If `a` is not an array, a
445 conversion is attempted.
446 axis : int, optional
447 Axis along which to average `a`. If `None`, averaging is done over
448 the flattened array.
449 weights : array_like, optional
450 An array of weights associated with the values in `a`. Each value in
451 `a` contributes to the average according to its associated weight.
452 The weights array can either be 1-D (in which case its length must be
453 the size of `a` along the given axis) or of the same shape as `a`.
454 If `weights=None`, then all data in `a` are assumed to have a
455 weight equal to one.
456 returned : bool, optional
457 Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`)
458 is returned, otherwise only the average is returned.
459 If `weights=None`, `sum_of_weights` is equivalent to the number of
460 elements over which the average is taken.
461
462
463 Returns
464 -------
465 average, [sum_of_weights] : {array_type, double}
466 Return the average along the specified axis. When returned is `True`,
467 return a tuple with the average as the first element and the sum
468 of the weights as the second element. The return type is `Float`
469 if `a` is of integer type, otherwise it is of the same type as `a`.
470 `sum_of_weights` is of the same type as `average`.
471
472 Raises
473 ------
474 ZeroDivisionError
475 When all weights along axis are zero. See `numpy.ma.average` for a
476 version robust to this type of error.
477 TypeError
478 When the length of 1D `weights` is not the same as the shape of `a`
479 along axis.
480
481 See Also
482 --------
483 mean
484
485 ma.average : average for masked arrays -- useful if your data contains
486 "missing" values
487
488 Examples
489 --------
490 >>> data = range(1,5)
491 >>> data
492 [1, 2, 3, 4]
493 >>> np.average(data)
494 2.5
495 >>> np.average(range(1,11), weights=range(10,0,-1))
496 4.0
497
498 >>> data = np.arange(6).reshape((3,2))
499 >>> data
500 array([[0, 1],
501 [2, 3],
502 [4, 5]])
503 >>> np.average(data, axis=1, weights=[1./4, 3./4])
504 array([ 0.75, 2.75, 4.75])
505 >>> np.average(data, weights=[1./4, 3./4])
506 Traceback (most recent call last):
507 ...
508 TypeError: Axis must be specified when shapes of a and weights differ.
509
510 """
511 1 13 13.0 0.0 if not isinstance(a, np.matrix):
512 1 16 16.0 0.0 a = np.asarray(a)
513
514 1 1 1.0 0.0 if weights is None:
515 avg = a.mean(axis)
516 scl = avg.dtype.type(a.size/avg.size)
517 else:
518 1 59659 59659.0 28.2 a = a + 0.0
519 1 19 19.0 0.0 wgt = np.array(weights, dtype=a.dtype, copy=0)
520
521 # Sanity checks
522 1 3 3.0 0.0 if a.shape != wgt.shape:
523 if axis is None:
524 raise TypeError(
525 "Axis must be specified when shapes of a and weights "
526 "differ.")
527 if wgt.ndim != 1:
528 raise TypeError(
529 "1D weights expected when shapes of a and weights differ.")
530 if wgt.shape[0] != a.shape[axis]:
531 raise ValueError(
532 "Length of weights not compatible with specified axis.")
533
534 # setup wgt to broadcast along axis
535 wgt = np.array(wgt, copy=0, ndmin=a.ndim).swapaxes(-1, axis)
536
537 1 30743 30743.0 14.6 scl = wgt.sum(axis=axis)
538 1 58 58.0 0.0 if (scl == 0.0).any():
539 raise ZeroDivisionError(
540 "Weights sum to zero, can't be normalized")
541
542 1 120706 120706.0 57.1 avg = np.multiply(a, wgt).sum(axis)/scl
543
544 1 2 2.0 0.0 if returned:
545 scl = np.multiply(avg, 0) + scl
546 return avg, scl
547 else:
548 1 1 1.0 0.0 return avg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment