search
Search
menu search toc more_vert
Guest 0reps
Thanks for the thanks!
close
account_circle
Profile
exit_to_app
Sign out
help Ask a question
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview Doc Search Code Search Beta SORRY NOTHING FOUND!
mic
Start speaking... Voice search is only supported in Safari and Chrome.
Shrink
Navigate to
A
A
brightness_medium
share
arrow_backShare Twitter Facebook

# NumPy | average method

NumPy
chevron_right
Documentation
schedule Jul 1, 2022
Last updated
local_offer PythonNumPy
Tags

Numpy's `average(~)` method computes the weighted average along the specified axis.

# Parameters

1. `a` | `array-like`

The input array.

2. `axis` | `None` or `int` or `tuple` of `int` | `optional`

The axis along which to compute the mean.

Axis

Meaning

0

Row-wise computation of mean

1

Column-wise computation of mean

None

All values used to compute the mean

3. `weights` | `axis` | `optional`

The array containing the weights. The dimension must be 1D with size equal to that of `a`, or the exact same shape as `a`. By default, `weights=None`, that is, a simple mean will be computed.

4. `return` | `boolean` | `optional`

Whether you want the sum of weights returned. By default `return=False`.

# Return value

If axis in unset, then a scalar is returned. Otherwise, a Numpy array of weighted averages is returned.

# Examples

## Basic usage

Consider the following:

``` a = np.array([1,2,3])np.average(a, weights=[0,2,4]) 2.6667 ```

Here, the weighted average is:

``` (1*0 + 2*2 + 3*4) / (0+2+4) = 2.6667 ```

## Getting the sum of the weighted average

To get the sum of the weighted used (i.e. `0+2+4=6`), set `returned=True`:

``` np.average([1,2,3], weights=[0,2,4], returned=True) (2.6666666666666665, 6.0) ```

## Computing the weighted average of a 2D array

Suppose we have the following 2D array:

``` a = np.array([[1,2],[3,4]])a array([[1, 2], [3, 4]]) ```

### Weighted average of all values

Computing the weighted average of all values:

``` np.average(a, weights=[[5,6],[7,8]]) 2.6923076923076925 ```

### Weighted average of each column

Computing the weighted average of each column, set `axis=0`:

``` np.average(a, weights=[[5,6],[7,8]], axis=0) array([2.16666667, 3.14285714]) ```

### Weighted average of each row

Computing the weighted average of each row, set `axis=1`:

``` np.average(a, weights=[[5,6],[7,8]], axis=1) array([1.54545455, 3.53333333]) ```
mail