python 的numpy庫中的mean()函數(shù)用法介紹
1. mean() 函數(shù)定義:
numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<class numpy._globals._NoValue at 0x40b6a26c>)[source]
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. float64intermediate and return values are used for integer inputs.
Parameters: |
a : array_like
axis : None or int or tuple of ints, optional
dtype : data-type, optional
out : ndarray, optional
keepdims : bool, optional
|
---|---|
Returns: |
m : ndarray, see dtype parameter above
|
2 mean()函數(shù)功能:求取均值
經常操作的參數(shù)為axis,以m * n矩陣舉例:
axis 不設置值,對 m*n 個數(shù)求均值,返回一個實數(shù)
axis = 0:壓縮行,對各列求均值,返回 1* n 矩陣
axis =1 :壓縮列,對各行求均值,返回 m *1 矩陣
舉例:
>>> import numpy as np >>> num1 = np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]]) >>> now2 = np.mat(num1) >>> now2 matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]) >>> np.mean(now2) # 對所有元素求均值 3.5 >>> np.mean(now2,0) # 壓縮行,對各列求均值 matrix([[ 2.5, 3.5, 4.5]]) >>> np.mean(now2,1) # 壓縮列,對各行求均值 matrix([[ 2.], [ 3.], [ 4.], [ 5.]])
補充拓展:numpy的np.nanmax和np.max區(qū)別(坑)
numpy的np.nanmax和np.array([1,2,3,np.nan]).max()的區(qū)別(坑)
原理
在計算dataframe最大值時,最先用到的一定是Series對象的max()方法(),最終結果是4。
s1 = pd.Series([1,2,3,4,np.nan])
s1_max = s1.max()
但是筆者由于數(shù)據(jù)量巨大,列數(shù)較多,于是為了加快計算速度,采用numpy進行最大值的計算,但正如以下代碼,最終結果得到的是nan,而非4。發(fā)現(xiàn),采用這種方式計算最大值,nan也會包含進去,并最終結果為nan。
s1 = pd.Series([1,2,3,4,np.nan]) s1_max = s1.values.max() >>>nan
通過閱讀numpy的文檔發(fā)現(xiàn),存在np.nanmax的函數(shù),可以將np.nan排除進行最大值的計算,并得到想要的正確結果。
當然不止是max,min 、std、mean 均會存在列中含有np.nan時,s1.values.min /std/mean ()返回nan的情況。
速度區(qū)別
速度由快到慢依次:
s1 = pd.Series([1,2,3,4,5,np.nan]) #速度由快至慢 np.nanmax(s1.values) > np.nanmax(s1) > s1.max()
以上這篇python 的numpy庫中的mean()函數(shù)用法介紹就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Pytorch使用Visdom進行數(shù)據(jù)可視化的示例代碼
pytorch Visdom可視化,是一個靈活的工具,用于創(chuàng)建,組織和共享實時豐富數(shù)據(jù)的可視化,這個博客簡要介紹一下在使用Pytorch進行數(shù)據(jù)可視化的一些內容,感興趣的朋友可以參考下2023-12-12python百行代碼自制電腦端網(wǎng)速懸浮窗的實現(xiàn)
這篇文章主要介紹了python百行代碼自制電腦端網(wǎng)速懸浮窗的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05