- Среднее значение NumPy() и среднее значение(): в чем разница?
- Пример 1: Используйте np.mean() и np.average() без весов
- Пример 2: Используйте np.average() с весами
- Дополнительные ресурсы
- numpy.average#
- numpy.mean#
- Библиотека Numpy. Расчет статистик по данным в массиве
- Введение
- Размерность массива
- Общие правила при работе с массивами Numpy
- Вызов функции расчета статистики
- Расчет статистик по строкам или столбцам массива
- Функции (методы) для расчета статистик в Numpy
- P.S.
Среднее значение NumPy() и среднее значение(): в чем разница?
Вы можете использовать функции np.mean() или np.average() для вычисления среднего значения массива в Python.
Вот тонкая разница между двумя функциями:
- np.mean всегда вычисляет среднее арифметическое.
- np.average имеет необязательный параметр веса , который можно использовать для вычисления средневзвешенного значения.
В следующих примерах показано, как использовать каждую функцию на практике.
Пример 1: Используйте np.mean() и np.average() без весов
Предположим, у нас есть следующий массив в Python, который содержит семь значений:
#create array of values data = [1, 4, 5, 7, 8, 8, 10]
Мы можем использовать np.mean() и np.average() для вычисления среднего значения этого массива:
import numpy as np #calculate average value of array np.mean (data) 6.142857142857143 #calcualte average value of array np.average (data) 6.142857142857143
Обе функции возвращают одно и то же значение.
Обе функции использовали следующую формулу для расчета среднего:
Среднее = (1 + 4 + 5 + 7 + 8 + 8 + 10) / 7 = 6,142857 …
Пример 2: Используйте np.average() с весами
Еще раз предположим, что у нас есть следующий массив в Python, который содержит семь значений:
#create array of values data = [1, 4, 5, 7, 8, 8, 10]
Мы можем использовать np.average() для вычисления средневзвешенного значения для этого массива, указав список значений для параметров веса :
import numpy as np #calculate weighted average of array np.average (data, weights=(.1, .2, .4, .05, .05, .1, .1)) 5.45
Средневзвешенное значение оказывается равным 5,45 .
Вот формула, которую np.average() использовал для вычисления этого значения:
Средневзвешенное значение = 1 * 0,1 + 4 * 0,2 + 5 * 0,4 + 7 * 0,05 + 8 * 0,05 + 8 * 0,1 + 10 * 0,1 = 5,45 .
Обратите внимание, что мы не могли использовать np.mean() для выполнения этого вычисления, поскольку эта функция не имеет параметра веса .
Обратитесь к документации NumPy для полного объяснения функций np.mean() и np.average() .
Дополнительные ресурсы
В следующих руководствах объясняется, как рассчитать другие средние значения в Python:
numpy.average#
Compute the weighted average along the specified axis.
Parameters : a array_like
Array containing data to be averaged. If a is not an array, a conversion is attempted.
axis None or int or tuple of ints, optional
Axis or axes along which to average a. The default, axis=None, will average over all of the elements of the input array. If axis is negative it counts from the last to the first axis.
If axis is a tuple of ints, averaging is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
weights array_like, optional
An array of weights associated with the values in a. Each value in a contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of a along the given axis) or of the same shape as a. If weights=None, then all data in a are assumed to have a weight equal to one. The 1-D calculation is:
avg = sum(a * weights) / sum(weights)
The only constraint on weights is that sum(weights) must not be 0.
returned bool, optional
Default is False. If True, the tuple ( average , sum_of_weights) is returned, otherwise only the average is returned. If weights=None, sum_of_weights is equivalent to the number of elements over which the average is taken.
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 original a. Note: keepdims will not work with instances of numpy.matrix or other classes whose methods do not support keepdims.
Return the average along the specified axis. When returned is True, return a tuple with the average as the first element and the sum of the weights as the second element. sum_of_weights is of the same type as retval. The result dtype follows a genereal pattern. If weights is None, the result dtype will be that of a , or float64 if a is integral. Otherwise, if weights is not None and a is non- integral, the result type will be the type of lowest precision capable of representing values of both a and weights. If a happens to be integral, the previous rules still applies but the result dtype will at least be float64 .
When all weights along axis are zero. See numpy.ma.average for a version robust to this type of error.
When the length of 1D weights is not the same as the shape of a along axis.
average for masked arrays – useful if your data contains “missing” values
Returns the type that results from applying the numpy type promotion rules to the arguments.
>>> data = np.arange(1, 5) >>> data array([1, 2, 3, 4]) >>> np.average(data) 2.5 >>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1)) 4.0
>>> data = np.arange(6).reshape((3, 2)) >>> data array([[0, 1], [2, 3], [4, 5]]) >>> np.average(data, axis=1, weights=[1./4, 3./4]) array([0.75, 2.75, 4.75]) >>> np.average(data, weights=[1./4, 3./4]) Traceback (most recent call last): . TypeError: Axis must be specified when shapes of a and weights differ.
>>> a = np.ones(5, dtype=np.float128) >>> w = np.ones(5, dtype=np.complex64) >>> avg = np.average(a, weights=w) >>> print(avg.dtype) complex256
With keepdims=True , the following result has shape (3, 1).
>>> np.average(data, axis=1, keepdims=True) array([[0.5], [2.5], [4.5]])
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
Библиотека Numpy. Расчет статистик по данным в массиве
Библиотека Numpy предоставляет функции для расчета простых статистик: среднее значение, медиана, стандартное отклонение и т.п. Вопросу использования данных функций посвящен этот урок.
Введение
Импортируйте библиотеку Numpy , если вы еще этого не сделали.
Для начала создадим матрицу, которая нам понадобится в работе.
>>> m = np.matrix('1 2 3 4; 5 6 7 8; 9 1 5 7') >>> print(m) [[1 2 3 4] [5 6 7 8] [9 1 5 7]]
В этом случае будет создан объект типа matrix .
Если вы уже работали с Numpy , это может для вас быть чем-то новым. В Numpy , как правило, приходится работать с объектами класса ndarray . Мы выбрали matrix из-за удобства объявления массива, т.к. matrix позволяет использование Matlab -подобный стиль, и, наверное, вам будет интересно познакомиться с чем-то новым. Для задач, рассматриваемых в рамках данной статьи, объекты matrix и ndarray одинаково хорошо подходят. Matix можно превратить в ndarray вот так:
В любом случае наша таблица чисел будет выглядеть следующим образом.
Размерность массива
Для определения размерности массива Numpy используйте атрибут shape .
В результате мы получим кортеж из двух элементов, первый из них – это количество строк, второй – столбцов.
Общие правила при работе с массивами Numpy
Перед тем, как перейти к описанию функций расчета статистик необходимо, чтобы вы запомнили несколько важных вещей, касательно функций и массивов Numpy .
Вызов функции расчета статистики
Для расчета той или иной статистики, соответствующую функцию можно вызвать как метод объекта, с которым вы работаете. Для нашего массива это будет выглядеть так.
Тот же результат можно получить вызвав библиотечную функцию с соответствующим именем, передав ей в качестве аргумента массив.
Расчет статистик по строкам или столбцам массива
Вызовем функцию вычисления статистики (максимальный элемент) без аргументов.
В этом случает будут обработаны все элементы массива.
Если необходимо найти максимальный элемент в каждой строке, то для этого нужно передать в качестве аргумента параметр axis=1 .
Для вычисления статистики по столбцам, передайте в качестве параметра аргумент axis=0 .
Функции (методы) для расчета статистик в Numpy
Ниже, в таблице, приведены методы объекта ndarray (или matrix ), которые, как мы помним из раздела выше, могут быть также вызваны как функции библиотеки Numpy , для расчета статистик по данным массива.
Имя метода | Описание |
argmax | Индексы элементов с максимальным значением (по осям) |
argmin | Индексы элементов с минимальным значением (по осям) |
max | Максимальные значения элементов (по осям) |
min | Минимальные значения элементов (по осям) |
mean | Средние значения элементов (по осям) |
prod | Произведение всех элементов (по осям) |
std | Стандартное отклонение (по осям) |
sum | Сумма всех элементов (по осям) |
var | Дисперсия (по осям) |
Вычислим некоторые из представленных выше статистик.
>>> m.mean() 4.833333333333333 >>> m.mean(axis=1) matrix([[2.5], [6.5], [5.5]]) >>> m.sum() 58 >>> m.sum(axis=0) matrix([[15, 9, 15, 19]])
P.S.
Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
>>