Среднее значение матрицы python

Python NumPy Average with Examples

In this Python tutorial, we will discuss Python NumPy Average and also cover the below examples:

  • Python numpy average vs mean
  • Python numpy average of columns
  • Python numpy average 2d array
  • Python numpy average function
  • Python numpy average ignore nan
  • Python numpy average of matrix
  • Python numpy moving average filter
  • Python numpy average value

Python numpy average

  • In this section, we will learn and discuss the Python numpy average.
  • To find the average of a numpy array, you can use numpy.average() function.
  • The numpy library of Python provides a function called np. average(), used for calculating the weight mean along the specified axis.

Here is the syntax of the NumPy average

numpy.average ( arr, axis=None, Weights=None, returned=False )
  • It consists of few parameters
    • arr: An array stored data to be averaged.
    • Axis: Axis along which to average a. The default, axis=None, will average over all the values of the input array. If the axis is negative it will counts from the end to the first axis.
    • Weights: It is an optional parameter. Each value in a contributes to the mean according to its given weight.
    • Returns: it will Return the average along the given axis. When the average value is True with the mean as the first element and the sum of the weights as the second element.

    Let’s take an example to check how to calculate numpy average in python.

    import numpy as np arr = np.arange(1, 5) avg = np.average(arr) print(avg)

    In the above code, we will import a NumPy library and create an array by using the function numpy.arange.

    Here is the Screenshot of the following given code

    Python numpy average

    Python numpy average vs mean

    • In this method, we will learn and discuss the numpy average vs mean.
    • Both these functions can be used to calculate the arithmetic and statistic value to find mean or average.
    • np.mean() function can have many other parameters like dtype, out, where and more which are not available in the np.average() function.
    • This function can compute a weighted mean if the weights parameter is supplied.
    • np.average does not take into boolean masks, so it will generate the average over the whole set of data. While the case of mean takes into boolean masks, so compute the mean only over unmasked values.
    import numpy as np arr = np.arange(1, 5) avg = np.average(arr) mea = np.mean(arr) print(avg) print(mea)

    Here is the Screenshot of the following given code

    Python numpy average vs mean

    Python numpy average of columns

    • In this method, we will learn and discuss the Python numpy average of columns.
    • np.average() function is to calculate mean values across dimensions in an array.
    • It will return the average of a numpy array of all values along the given axis.
    • x as equal to 0 and then 1 to calculate the mean value of each column and then row in numpy module
    numpy.average ( arr, axis=None, Weights=None, returned=False )
    import numpy as np arr = np.array([[2,3,4], [3,6,7], [5,7,8]]) a= np.average(arr,axis=0) print(a)

    Here is the Screenshot of the following given code

    Python numpy average of columns

    Python numpy average 2d array

    • In this method, we will learn and discuss the Python numpy average 2d array.
    • To calculate the average of all values in a 2 dimensional NumPy array called matrix, use the numpy.average(matrix) function.
    • The output will display a numpy array that has three average values, one per column of the input given array.

    Here is the Syntax of the numpy average

    numpy.average ( arr, axis=None, Weights=None, returned=False )
    import numpy as np arr = np.array([[4,5,6], [4,6,7]])# 2D array a= np.average(arr) print(a)

    Here is the Screenshot of the following given code

    Python numpy average 2d array

    Python numpy average function

    • In this method, we will learn and discuss the numpy average function
    • The numpy library of Python provides a function called numpy.average(). Basically, it is used for calculating the weighted average along the given axis.
    • To find the mean of a numpy array, you can use np.average() statistical function.
    • These weights will be multiplied with the values and then the mean of the resulting is calculated.

    Here is the Syntax of the NumPy average function

    numpy.average ( arr, axis=None, Weights=None, returned=False )
    import numpy as np c = np.array([2, 3, 4, 7]).reshape(2,2) d = np.average(c, axis=0, weights=[0.3,0.7])# average along axis=0 print(d)

    Here is the Screenshot of the following given code

    Python numpy average function

    Python numpy average ignore nan

    • In this method, we will learn and discuss the numpy average ignore nan.
    • If the numpy array has a NaN value and we can easily find out the average without the effect of the NaN value. axis: we can use axis=1 means row-wise or column-wise.
    • In this method, we will calculate our weighted average and create a numpy array.
    • numpy.average does take into account masks, so it will generate the average over the whole set of data. While in case of average takes into boolean masks, so compute the mean only over unmasked values.
    import numpy as np avg = np.array([[4,5,6], [7,8,np.NaN], [np.NaN,6,np.NaN], [0,0,0]]) data = np.ma.masked_array(avg, np.isnan(avg)) weights = [1, 1, 1] average = np.ma.average(data, axis=1, weights=weights) result = average.filled(np.nan) print(result)

    Here is the Screenshot of the following given code

    Python numpy average ignore nan

    Python numpy average of matrix

    • In this method, we will learn and discuss the numpy average matrix.
    • To calculate the average individually for each column of the 2Dimension matrix, use the function call numpy. average(array, axis=0) setting the axis parameter to 0.
    • It will always return the mean value of the matrix.
    • In this method, we can easily use the function np.average().
    import numpy as np x = np.matrix(np.arange(12).reshape((3, 4))) y = np.average(x) print(y)

    Here is the Screenshot of the following given code

    Python numpy average of matrix

    Python numpy average filter

    • In this method, we will learn and discuss the numpy moving average filter.
    • In Python the np. average() is used in time-series data by measuring the average of the data at given intervals.
    • In this method we can easily use the function numpy.convolve to measure the moving average for numpy arrays.
    import numpy as np def moving_average(x, w): return np.convolve(x, np.ones(w), 'valid') / w data = np.array([2,3,8,4,6,7,8,11,14,17,9,7]) print(moving_average(data,4))

    Here is the Screenshot of the following given code

    Python numpy average filter

    Another way to calculate the average for NumPy arrays using scipy.convolve() function.

    The scipy.convolve() function in the same way. It is consumed to be a little faster. Another way to check the moving mean using the Python module is with the cumsum() function.

    import numpy as np def average(a, n) : ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n data = np.array([5,4,3,2,10,11,13,14,15,16,19,7]) print(average(data,4))

    Here is the Screenshot of the following given code

    Python numpy average moving filter

    Another method to calculate the moving average for NumPy arrays using a bottleneck.

    The bottleneck module is a compilation of quick NumPy modules. This module has the move_average() function, which can return the moving average of some data.

    import numpy as np import bottleneck as bn import numpy as np def rollavg_bottlneck(a,n): return bn.move_mean(a, window=n,min_count = None) data = np.array([10,5,8,9,15,22,26,11,15,16,18,7]) print(rollavg_bottlneck(data, 4))

    Here is the Screenshot of the following given code

    Python numpy moving average bottleneck

    Python numpy average value

    • In this method, we will learn and discuss the numpy average value.
    • In this method, we will check how to use the function np.average() to evaluate the average value of a given array.
    • This function returns the arithmetic statistics average value of elements in the array.
    • Else on the given axis, float 64 datatypes is compute as well as return values are used for integer inputs.

    Here is the Syntax of the NumPy average

    numpy.average ( arr, axis=None, Weights=None, returned=False )
    import numpy as np arr = np.array([[1,2,4], [3,4,7], [5,7,8]]) a= np.average(arr,axis=0) print(a)

    Here is the Screenshot of the following given code

    Python numpy average value

    You may like the following Python NumPy articles:

    In this Python tutorial, we will discuss Python NumPy Average and also cover the below examples:

    • Python numpy average vs mean
    • Python numpy average of columns
    • Python numpy average 2d array
    • Python numpy average function
    • Python numpy average ignore nan
    • Python numpy average of matrix
    • Python numpy moving average filter
    • Python numpy average value

    I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

    Источник

    numpy.mean#

    Compute the arithmetic mean along the specified axis.

    Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

    Parameters : a array_like

    Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

    axis None or int or tuple of ints, optional

    Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

    If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as before.

    dtype data-type, optional

    Type to use in computing the mean. For integer inputs, the default is float64 ; for floating point inputs, it is the same as the input dtype.

    out ndarray, optional

    Alternate output array in which to place the result. The default is None ; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See Output type determination for more details.

    keepdims bool, optional

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray , however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

    where array_like of bool, optional

    Elements to include in the mean. See reduce for details.

    If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned.

    The arithmetic mean is the sum of the elements along the axis divided by the number of elements.

    Note that for floating-point input, the mean is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-precision accumulator using the dtype keyword can alleviate this issue.

    By default, float16 results are computed using float32 intermediates for extra precision.

    >>> a = np.array([[1, 2], [3, 4]]) >>> np.mean(a) 2.5 >>> np.mean(a, axis=0) array([2., 3.]) >>> np.mean(a, axis=1) array([1.5, 3.5]) 

    In single precision, mean can be inaccurate:

    >>> a = np.zeros((2, 512*512), dtype=np.float32) >>> a[0, :] = 1.0 >>> a[1, :] = 0.1 >>> np.mean(a) 0.54999924 

    Computing the mean in float64 is more accurate:

    >>> np.mean(a, dtype=np.float64) 0.55000000074505806 # may vary 

    Specifying a where argument:

    >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]]) >>> np.mean(a) 12.0 >>> np.mean(a, where=[[True], [False], [False]]) 9.0 

    Источник

    Читайте также:  Nuxt typescript composition api
Оцените статью