- Функция numpy.prod() в Python: синтаксис, параметры и примеры
- Что такое функция np.prod() в Python?
- Синтаксис
- Параметры
- Возвращаемое значение
- Примеры
- numpy.prod#
- numpy.prod#
- NumPy prod()
- Introduction to to the NumPy prod() function
- NumPy prod() function examples
- 1) Using the numpy prod() function with 1-D array example
- 2) Using the numpy prod() function with multidimensional array examples
- 3) Selecting numbers to include in the product
- 4) Special cases
- Summary
Функция numpy.prod() в Python: синтаксис, параметры и примеры
Чтобы найти произведение массива в Python, используйте метод numpy.prod(). Он возвращает произведение массива, предоставленного данной осью.
Что такое функция np.prod() в Python?
numpy.prod() в Python — это метод математической библиотеки numpy, который возвращает произведение элементов массива по заданной оси. По умолчанию для оси установлено значение «None», таким образом вычисляется произведение всех элементов в данном массиве. Функция prod() принимает до семи аргументов, некоторые могут быть необязательными.
Синтаксис
Параметры
- arr1: это параметр, который следует интерпретировать как array_like, действующий как входные данные.
- axis: [Необязательный параметр] Это может быть целое число, кортеж целых чисел или None. Этот параметр указывает оси, по которым должно выполняться изделие. Для отрицательной оси произведение вычисляется от последней до первой оси. Произведение выполняется по всем указанным для кортежа целым числам.
- dtype: [Необязательный параметр] Указывает тип возвращаемого массива. Он также устанавливает накопитель, в котором должны быть перемножены элементы входного массива arr1. Если arr1 не имеет целочисленного dtype меньшей точности, чем целое число платформы по умолчанию, используется dtype arr1. Если arr1 знаковый, то dtype представляет собой целое число платформы или целое число без знака той же точности, если arr1 беззнаковое.
- out:(ndarray) [Необязательный параметр]: указывает альтернативный выходной массив, в который должен быть помещен результирующий продукт. Должен иметь ту же форму, что и ожидаемый результат.
- keepdims:(bool) [Необязательный параметр] Если установлено значение true, уменьшенные оси остаются в качестве измерений с размером 1 в результате. Это делается для того, чтобы результирующая трансляция корректно относилась к массиву, взятому на вход.
- Initial:(скаляр) [Необязательный параметр]: это начальное значение продукта.
- where:(array_like of bool) [Необязательный параметр]: это элементы, которые должны быть включены в продукт.
Возвращаемое значение
Произведение массива элементов по заданной оси. Возвращает ссылку на массив out, если указано.
Примечание: если входной массив пуст, то этот метод возвращает нейтральный элемент: 1
Примеры
Следующий код демонстрирует использование метода prod().
numpy.prod#
Return the product of array elements over a given axis.
Parameters : a array_like
axis None or int or tuple of ints, optional
Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.
If axis is a tuple of ints, a product is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
dtype dtype, optional
The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.
out ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.
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 prod 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.
initial scalar, optional
The starting value for this product. See reduce for details.
Elements to include in the product. See reduce for details.
An array shaped as a but with the specified axis removed. Returns a reference to out if specified.
Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bit platform:
>>> x = np.array([536870910, 536870910, 536870910, 536870910]) >>> np.prod(x) 16 # may vary
The product of an empty array is the neutral element 1:
By default, calculate the product of all elements:
Even when the input array is two-dimensional:
>>> a = np.array([[1., 2.], [3., 4.]]) >>> np.prod(a) 24.0
But we can also specify the axis over which to multiply:
>>> np.prod(a, axis=1) array([ 2., 12.]) >>> np.prod(a, axis=0) array([3., 8.])
Or select specific elements to include:
>>> np.prod([1., np.nan, 3.], where=[True, False, True]) 3.0
If the type of x is unsigned, then the output type is the unsigned platform integer:
>>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uint True
If x is of a signed integer type, then the output type is the default platform integer:
>>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == int True
You can also start the product with a value other than one:
numpy.prod#
Return the product of array elements over a given axis.
Parameters : a array_like
axis None or int or tuple of ints, optional
Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.
If axis is a tuple of ints, a product is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
dtype dtype, optional
The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.
out ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.
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 prod 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.
initial scalar, optional
The starting value for this product. See reduce for details.
Elements to include in the product. See reduce for details.
An array shaped as a but with the specified axis removed. Returns a reference to out if specified.
Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bit platform:
>>> x = np.array([536870910, 536870910, 536870910, 536870910]) >>> np.prod(x) 16 # may vary
The product of an empty array is the neutral element 1:
By default, calculate the product of all elements:
Even when the input array is two-dimensional:
>>> a = np.array([[1., 2.], [3., 4.]]) >>> np.prod(a) 24.0
But we can also specify the axis over which to multiply:
>>> np.prod(a, axis=1) array([ 2., 12.]) >>> np.prod(a, axis=0) array([3., 8.])
Or select specific elements to include:
>>> np.prod([1., np.nan, 3.], where=[True, False, True]) 3.0
If the type of x is unsigned, then the output type is the unsigned platform integer:
>>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uint True
If x is of a signed integer type, then the output type is the default platform integer:
>>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == int True
You can also start the product with a value other than one:
NumPy prod()
Summary: in this tutorial, you’ll learn how to use the numpy prod() function to calculate the product of numbers in an array.
Introduction to to the NumPy prod() function
Suppose you have three numbers n, m, and k. The product of the three numbers is nxmxk. For example, the product of 2, 3, and 4 is 2x3x4 = 24.
To calcualte the products of numbers in an aray, you use the numpy prod() function:
numpy.prod(a, axis=None, dtype=None, out=None, keepdims=, initial=, where=)
Code language: Python (python)
NumPy prod() function examples
Let’s take some example of using the numpy prod() function.
1) Using the numpy prod() function with 1-D array example
The following example uses the prod() to calculate the products of numbers in a 1-D array:
import numpy as np a = np.arange(1, 5) result = np.prod(a) print(a) print(f'result= ')
Code language: Python (python)
[1 2 3 4] result=24
Code language: Python (python)
First, create an array that has 4 numbers from 1 to 4 using the arange() function.
a = np.arange(1, 5)
Code language: Python (python)
Second, calculate the products of all the numbers in the array a:
result = np.prod(a)
Code language: Python (python)
Third, display the numbers of the array a and their product:
print(a) print(f'result= ')
Code language: Python (python)
Note that you can pass an array like object to the prod() function e.g., a list. For example:
import numpy as np result = np.prod([1, 2, 3, 4, 5]) print(f'result= ')
Code language: Python (python)
result=120
Code language: Python (python)
2) Using the numpy prod() function with multidimensional array examples
The following example uses the prod() to calcualte products of all numbers in a 2-D array:
import numpy as np result = np.prod([ [1, 2], [3, 4] ]) print(f'result= ')
Code language: Python (python)
result=24
Code language: Python (python)
To calcualte product of numbers of an axis, you can specify the axis argument. For example, the following uses the prod() to calculate the product of numbers on axis 0:
import numpy as np result = np.prod([ [1, 2], [3, 4] ], axis=0) print(f'result= ')
Code language: Python (python)
result=[3 8]
Code language: Python (python)
Similarly, you can calculate the product of numbers on axis 1:
import numpy as np result = np.prod([ [1, 2], [3, 4] ], axis=1) print(f'result= ')
Code language: Python (python)
result=[ 2 12]
Code language: Python (python)
3) Selecting numbers to include in the product
To select specific number to include in the product, you use the where argument. For example:
import numpy as np a = np.array([np.nan, 3, 4]) result = np.prod(a, where=[False, True, True]) print(result)
Code language: Python (python)
12.0
Code language: Python (python)
In this example, the array contains three elements np.nan, 3, and 4.
The where argument uses a boolean list to specify which element in the array a should be included in the product.
If the value of the where list is True , the corresponding element of the input array will be included in the product.
4) Special cases
Note that if you pass an array of integers to the prod() function that causes an overflow, the prod() won’t raise the error. For example:
import numpy as np result = np.prod(np.arange(1, 100)) print(f'result= ')
Code language: Python (python)
result=0
Code language: Python (python)
The prod() function returns 1 if the array is empty. For example:
import numpy as np result = np.prod(np.array([])) print(f'result= ')
Code language: Python (python)
1.0
Code language: Python (python)