我在 3 个具有形状的数组中有一些数据:
docLengths.shape = (10000,)
docIds.shape = (10000,)
docCounts.shape = (68,10000)
我想获得某些 i 的相对计数及其平均值和标准差:
docRelCounts = docCounts/docLengths
relCountMeans = docRelCounts[i,:].mean()
relCountDeviations = docRelCounts[i,:].std()
问题是,docLengths 的某些元素为零。这会在 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
的值。
关于python - 如何从 ndarray 集合中删除与其中一个数组的零元素相对应的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5673984/