我有一些数据在3个数组形状:
docLengths.shape = (10000,)
docIds.shape = (10000,)
docCounts.shape = (68,10000)
我想获得一些I的相对计数及其均值和标准差:
docRelCounts = docCounts/docLengths
relCountMeans = docRelCounts[i,:].mean()
relCountDeviations = docRelCounts[i,:].std()
问题是,有些元素的doclength为零。这会在docRelCounts中产生NaN元素,因此平均值和偏差也是NaN。
我需要删除零长度文档的数据。我可以编写一个循环,定位零长度的文档并删除它们,但我希望有一些numpy数组魔法可以更有效地完成此操作。什么好主意吗?
试试这个:
docRelCounts = docCounts/docLengths
goodDocRelCounts = docRelCounts[i,:][np.invert(np.isnan(docRelCounts[i,:]))]
relCountMeans = goodDocRelCounts.mean()
relCountDeviations = goodDocRelCounts.std()
np.isnan
返回与True
形状相同的数组,其中原始数组为NaN
, False
在其他地方。np.invert
将其颠倒,然后你得到goodDocRelCounts
,只有NaN
以外的值。
使用from scipy.stats:
from scipy.stats import nanmean, nanstd
最后我这样做了(实际上我在看到eumiro的答案之前就已经解决了-它更简单了一点,但其他方面并没有更好,只是不同,所以我想我应该包括它:)
goodData = docLengths!=0 # find zero elements
docLen = docLen[goodData]
docCounts = docCounts[:,goodData]
docRelCounts = docCounts/docLen
means = map(lambda x:x.mean(), docRelCounts)
stds = map(lambda x:x.std(), docRelCounts)