PYTHON-numpy.mean

1.定义:

numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>)
#a:数组(不是数组就转为数组)
#axis:可选(不选择就是全部数的平均值)为0求各列平均值,为1求各行平均值
#dtype数据类型,可选,用于计算平均值的类型。对于整数输入,默认float64; 对于浮点输入,它与输入dtype相同。
#ndarray,可选,放置结果的备用输出数组。默认值为None; 如果提供的话,它的形状必须与预期的输出形状相同,但是如果需要的话,将强制转换类型。
#输出:如果out = None,则返回一个包含平均值的新数组,否则返回对输出数组的引用。

2.例子:

2.1 数组:

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

  >>> type(np.mean(a,axis = 1))
  <class 'numpy.ndarray'>

对数组而说,直接返回1*n的 array(数组)

2.2 矩阵:

>>> num1 = np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]])
>>> num1
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]])
>>> num2 = np.mat(num1)
>>> num2
matrix([[1, 2, 3],
        [2, 3, 4],
        [3, 4, 5],
        [4, 5, 6]])
>>> type(num2)
<class 'numpy.matrix'>
>>> num3 = np.asmatrix(num1)
>>> num3
matrix([[1, 2, 3],
        [2, 3, 4],
        [3, 4, 5],
        [4, 5, 6]])
>>> type(num3)
<class 'numpy.matrix'>
>>> np.mean(num2,axis = 0)
matrix([[2.5, 3.5, 4.5]])
>>> np.mean(num2,axis = 0)
matrix([[2.5, 3.5, 4.5]])
>>> np.mean(num2,axis = 1)
matrix([[2.],
        [3.],
        [4.],
        [5.]])
#说明:
#mat == asmatrix转换为矩阵
#矩阵的话:
#axis = 0,计算列均值,返回1*n
#axis = 1,计算行进制,返回m*1

 

3.参考代码:

官网:https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html

np.mat():https://www.jb51.net/article/161915.htm

https://blog.csdn.net/yeler082/article/details/90342438

np.mean:https://blog.csdn.net/lilong117194/article/details/78397329

posted @ 2020-04-17 20:12  落月_YU  阅读(836)  评论(0编辑  收藏  举报