如何计算矩阵中的矩阵平均值,但是要从计算中删除nan
值? (对于R人,请考虑na.rm = TRUE
)。
这是我的[非]工作示例:
import numpy as np
dat = np.array([[1, 2, 3],
[4, 5, np.nan],
[np.nan, 6, np.nan],
[np.nan, np.nan, np.nan]])
print(dat)
print(dat.mean(1)) # [ 2. nan nan nan]
删除NaN后,我的预期输出为:
array([ 2., 4.5, 6., nan])
答案 0 :(得分:35)
我认为你想要的是一个蒙面数组:
dat = np.array([[1,2,3], [4,5,nan], [nan,6,nan], [nan,nan,nan]])
mdat = np.ma.masked_array(dat,np.isnan(dat))
mm = np.mean(mdat,axis=1)
print mm.filled(np.nan) # the desired answer
编辑:合并所有时间数据
from timeit import Timer
setupstr="""
import numpy as np
from scipy.stats.stats import nanmean
dat = np.random.normal(size=(1000,1000))
ii = np.ix_(np.random.randint(0,99,size=50),np.random.randint(0,99,size=50))
dat[ii] = np.nan
"""
method1="""
mdat = np.ma.masked_array(dat,np.isnan(dat))
mm = np.mean(mdat,axis=1)
mm.filled(np.nan)
"""
N = 2
t1 = Timer(method1, setupstr).timeit(N)
t2 = Timer("[np.mean([l for l in d if not np.isnan(l)]) for d in dat]", setupstr).timeit(N)
t3 = Timer("np.array([r[np.isfinite(r)].mean() for r in dat])", setupstr).timeit(N)
t4 = Timer("np.ma.masked_invalid(dat).mean(axis=1)", setupstr).timeit(N)
t5 = Timer("nanmean(dat,axis=1)", setupstr).timeit(N)
print 'Time: %f\tRatio: %f' % (t1,t1/t1 )
print 'Time: %f\tRatio: %f' % (t2,t2/t1 )
print 'Time: %f\tRatio: %f' % (t3,t3/t1 )
print 'Time: %f\tRatio: %f' % (t4,t4/t1 )
print 'Time: %f\tRatio: %f' % (t5,t5/t1 )
返回:
Time: 0.045454 Ratio: 1.000000
Time: 8.179479 Ratio: 179.950595
Time: 0.060988 Ratio: 1.341755
Time: 0.070955 Ratio: 1.561029
Time: 0.065152 Ratio: 1.433364
答案 1 :(得分:18)
如果效果很重要,则应使用bottleneck.nanmean()
代替:
答案 2 :(得分:12)
答案 3 :(得分:8)
也可以动态创建带有nans过滤掉的蒙面数组:
print np.ma.masked_invalid(dat).mean(1)
答案 4 :(得分:8)
您始终可以找到以下内容的解决方法:
numpy.nansum(dat, axis=1) / numpy.sum(numpy.isfinite(dat), axis=1)
Numpy 2.0的numpy.mean
有一个skipna
选项可以解决这个问题。
答案 5 :(得分:3)
这是基于JoshAdel建议的解决方案。
定义以下功能:
def nanmean(data, **args):
return numpy.ma.filled(numpy.ma.masked_array(data,numpy.isnan(data)).mean(**args), fill_value=numpy.nan)
使用示例:
data = [[0, 1, numpy.nan], [8, 5, 1]]
data = numpy.array(data)
print data
print nanmean(data)
print nanmean(data, axis=0)
print nanmean(data, axis=1)
将打印出来:
[[ 0. 1. nan]
[ 8. 5. 1.]]
3.0
[ 4. 3. 1.]
[ 0.5 4.66666667]
答案 6 :(得分:2)
如何使用Pandas来做到这一点:
import numpy as np
import pandas as pd
dat = np.array([[1, 2, 3], [4, 5, np.nan], [np.nan, 6, np.nan], [np.nan, np.nan, np.nan]])
print dat
print dat.mean(1)
df = pd.DataFrame(dat)
print df.mean(axis=1)
给出:
0 2.0
1 4.5
2 6.0
3 NaN
答案 7 :(得分:2)
从numpy 1.8(2013-10-30发布)开始,nanmean
完全符合您的需求:
>>> import numpy as np
>>> np.nanmean(np.array([1.5, 3.5, np.nan]))
2.5
答案 8 :(得分:1)
或者你使用新上传的laxarray,这是一个蒙面数组的包装器。
import laxarray as la
la.array(dat).mean(axis=1)
按照JoshAdel的协议,我得到了:
Time: 0.048791 Ratio: 1.000000
Time: 0.062242 Ratio: 1.275689 # laxarray's one-liner
所以laxarray稍慢(需要检查原因,可能是可修复的),但更容易使用并允许使用字符串标注尺寸。
结帐:https://github.com/perrette/laxarray
编辑:我已经检查了另一个模块,“la”,拉里,它击败了所有测试:import la
la.larry(dat).mean(axis=1)
By hand, Time: 0.049013 Ratio: 1.000000
Larry, Time: 0.005467 Ratio: 0.111540
laxarray Time: 0.061751 Ratio: 1.259889
令人印象深刻!
答案 9 :(得分:0)
对所有提议的方法进行一次速度检查:
Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Jan 19 2016, 12:08:31) [MSC v.1500 64 bit (AMD64)]
IPython 4.0.1 -- An enhanced Interactive Python.
import numpy as np
from scipy.stats.stats import nanmean
dat = np.random.normal(size=(1000,1000))
ii = np.ix_(np.random.randint(0,99,size=50),np.random.randint(0,99,size=50))
dat[ii] = np.nan
In[185]: def method1():
mdat = np.ma.masked_array(dat,np.isnan(dat))
mm = np.mean(mdat,axis=1)
mm.filled(np.nan)
In[190]: %timeit method1()
100 loops, best of 3: 7.09 ms per loop
In[191]: %timeit [np.mean([l for l in d if not np.isnan(l)]) for d in dat]
1 loops, best of 3: 1.04 s per loop
In[192]: %timeit np.array([r[np.isfinite(r)].mean() for r in dat])
10 loops, best of 3: 19.6 ms per loop
In[193]: %timeit np.ma.masked_invalid(dat).mean(axis=1)
100 loops, best of 3: 11.8 ms per loop
In[194]: %timeit nanmean(dat,axis=1)
100 loops, best of 3: 6.36 ms per loop
In[195]: import bottleneck as bn
In[196]: %timeit bn.nanmean(dat,axis=1)
1000 loops, best of 3: 1.05 ms per loop
In[197]: from scipy import stats
In[198]: %timeit stats.nanmean(dat)
100 loops, best of 3: 6.19 ms per loop
所以最好的是'bottleneck.nanmean(dat,axis = 1)'
'scipy.stats.nanmean(dat)'并不比numpy.nanmean(dat, axis=1)
快。
答案 10 :(得分:0)
# I suggest you this way:
import numpy as np
dat = np.array([[1, 2, 3], [4, 5, np.nan], [np.nan, 6, np.nan], [np.nan, np.nan, np.nan]])
dat2 = np.ma.masked_invalid(dat)
print np.mean(dat2, axis=1)
答案 11 :(得分:-1)
'''define dataMat'''
numFeat= shape(datMat)[1]
for i in range(numFeat):
meanVal=mean(dataMat[nonzero(~isnan(datMat[:,i].A))[0],i])