is a function in the NumPy library that calculates the arithmetic mean (i.e., mean) of a given array or array element. The arithmetic average is the result of summing all values and dividing them by the number of values. It is a commonly used statistic that represents the central trend of a set of data.
Function prototype
(a, axis=None, dtype=None, out=None, keepdims=<no value>)
Parameter description
-
a
: The input data can be a one-dimensional or multi-dimensional array. -
axis
: Specifies which axis to calculate the average value. Default isNone
, means to calculate the average value after flattening the array into a one-dimensional array. If an axis is specified (such as0
or1
), then the average value of each column or row is calculated along the specified axis. -
dtype
: The type used to calculate the mean. By default, for inputs of integer types, usefloat64
, while for inputs of floating point type, the same type as the input is used. -
out
: Optional parameter, an alternative array for storing the results. Its shape must match the expected output shape. -
keepdims
: If set toTrue
, then the calculated axis will be the dimension that keeps the dimension of 1. This is very useful when you want the result to be broadcast back to the original array.
Example
Calculate the average value of a one-dimensional array
import numpy as np data = ([1, 2, 3, 4, 5]) mean_value = (data) print("Mean:", mean_value) # Output: Mean: 3.0
Calculate the average value of a two-dimensional array
import numpy as np data = ([[1, 2, 3], [4, 5, 6]]) mean_all = (data) # Do not specify axis, calculate the average value of the entire arraymean_axis_0 = (data, axis=0) # Calculate the average along the first axis (column)mean_axis_1 = (data, axis=1) # Calculate the average along the second axis (row) print("Mean of all elements:", mean_all) # Output: Mean of all elements: 3.5print("Mean along axis 0 (columns):", mean_axis_0) # Output: Mean along axis 0 (columns): [2.5 3.5 4.5]print("Mean along axis 1 (rows):", mean_axis_1) # Output: Mean along axis 1 (rows): [2. 5.]
From these examples, it can be seen thatis a simple and powerful method for calculating the average value of arrays of various types and sizes. This is very useful for processing and understanding data sets in applications such as data analysis and machine learning.
This is the end of this article about the specific use of the NumPy library. For more related NumPy content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!