【问题标题】:How to count the occurrence of certain item in an ndarray?如何计算ndarray中某些项目的出现?
【发布时间】:2015-04-24 04:34:33
【问题描述】:

在 Python 中,我有一个 ndarray y 打印为array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

我试图计算这个数组中有多少0s 和多少1s。

但是当我输入y.count(0)y.count(1) 时,它会显示

numpy.ndarray 对象没有属性count

我该怎么办?

【问题讨论】:

  • 这种情况下,也可以简单的使用numpy.count_nonzero

标签: python numpy multidimensional-array count


【解决方案1】:
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

如果你知道他们只是01

np.sum(y)

给你个数。 np.sum(1-y) 给出零。

为了稍微笼统,如果您想计算 0 而不是零(但可能是 2 或 3):

np.count_nonzero(y)

给出非零的数量。

但如果您需要更复杂的东西,我认为 numpy 不会提供一个不错的 count 选项。在这种情况下,请转到集合:

import collections
collections.Counter(y)
> Counter({0: 8, 1: 4})

这就像一个字典

collections.Counter(y)[0]
> 8

【讨论】:

    猜你喜欢
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2016-10-15
    • 2011-07-02
    • 1970-01-01
    相关资源
    最近更新 更多