使用numpy對(duì)數(shù)組求平均時(shí)如何忽略nan值
numpy對(duì)數(shù)組求平均時(shí)忽略nan值
在對(duì)numpy數(shù)組求平均np.mean()或者求數(shù)組中最大最小值np.max()/np.min()時(shí),如果數(shù)組中有nan,此時(shí)求得的結(jié)果為:nan,那么該如何忽略其中的nan呢?
此時(shí)應(yīng)該用另一個(gè)方法
np.nanmean(),np.nanmax(),np.nanmin()
使用np.mean()的效果

使用np.nanmean()的效果

numpy含nan值進(jìn)行歸一化操作
方法一
import numpy as np
A = np.array([[ 7, 4, 5, 7000],
[ 1, 900, 9, nan],
[ 5, -1000, nan, 100],
[nan, nan, 3, 1000]])
#Compute NaN-norms
L1_norm = np.nansum(np.abs(A), axis=1)
L2_norm = np.sqrt(np.nansum(A**2, axis=1))
max_norm = np.nanmax(np.abs(A), axis=1)
#Normalize rows
A_L1 = A / L1_norm[:,np.newaxis] # A.values if Dataframe
A_L2 = A / L2_norm[:,np.newaxis]
A_max = A / max_norm[:,np.newaxis]
#Check that it worked
L1_norm_after = np.nansum(np.abs(A_L1), axis=1)
L2_norm_after = np.sqrt(np.nansum(A_L2**2, axis=1))
max_norm_after = np.nanmax(np.abs(A_max), axis=1)
In[182]: L1_norm_after
Out[182]: array([1., 1., 1., 1.])
In[183]: L2_norm_after
Out[183]: array([1., 1., 1., 1.])
In[184]: max_norm_after
Out[184]: array([1., 1., 1., 1.])
方法二
rom numpy import nan, nanmean
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
A = [[ 7, 4, 5, 7000],
[ 1, 900, 9, nan],
[ 5, -1000, nan, 100],
[nan, nan, 3, 1000]]
scaler.fit(A)
In [45]: scaler.mean_
Out[45]: array([4.33333333, -32., 5.66666667, 2700.])
In [46]: scaler.transform(A)
Out[46]: array([[ 1.06904497, 0.04638641, -0.26726124, 1.40399977],
[-1.33630621, 1.20089267, 1.33630621, nan],
[ 0.26726124, -1.24727908, nan, -0.84893009],
[ nan, nan, -1.06904497, -0.55506968]])
In [54]: nanmean(scaler.transform(A), axis=0)
Out[54]: array([ 1.48029737e-16, 0.00000000e+00, -1.48029737e-16,0.00000000e+00])
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python docutils文檔編譯過(guò)程方法解析
這篇文章主要介紹了Python docutils文檔編譯過(guò)程方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
python海龜繪圖之畫(huà)國(guó)旗實(shí)例代碼
這篇文章主要給大家介紹了關(guān)于python海龜繪圖之畫(huà)國(guó)旗的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
python人物視頻背景替換實(shí)現(xiàn)虛擬空間穿梭
這篇文章主要為大家介紹了python實(shí)現(xiàn)人物視頻背景替換示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Python 使用ConfigParser操作ini配置文件
這篇文章主要介紹了Python 使用ConfigParser操作ini配置文件的相關(guān)資料,需要的朋友可以參考下2023-05-05
PyQt5 控件字體樣式等設(shè)置的實(shí)現(xiàn)
這篇文章主要介紹了PyQt5 控件字體樣式等設(shè)置的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
python實(shí)現(xiàn)自動(dòng)整理文件
這篇文章主要介紹了python實(shí)現(xiàn)自動(dòng)整理文件,主要內(nèi)容通過(guò)整理桌面雜亂無(wú)章都是文檔和資料了解用python如何批量將不同后綴的文件移動(dòng)到同一文件夾,需要的朋友可以參考一下2022-04-04
查看TensorFlow checkpoint文件中的變量名和對(duì)應(yīng)值方法
今天小編就為大家分享一篇查看TensorFlow checkpoint文件中的變量名和對(duì)應(yīng)值方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06

