如何计算 ndarray 中某个项目的出现次数?

How to count the occurrence of certain item in an ndarray?

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

我正在计算这个数组中有多少 0 和多少 1

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

numpy.ndarray object has no attribute count

我该怎么办?

a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
unique, counts = numpy.unique(a, return_counts=True)
dict(zip(unique, counts))

# {0: 7, 1: 4, 2: 1, 3: 2, 4: 1}

非numpy方式:

使用collections.Counter;

import collections, numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
collections.Counter(a)

# Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 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

将数组 y 转换为列表 l,然后执行 l.count(1)l.count(0)

>>> y = numpy.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
>>> l = list(y)
>>> l.count(1)
4
>>> l.count(0)
8 

对于您的情况,您还可以查看 numpy.bincount

In [56]: a = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

In [57]: np.bincount(a)
Out[57]: array([8, 4])  #count of zeros is at index 0 : 8
                        #count of ones is at index 1 : 4

我会使用 np.where:

how_many_0 = len(np.where(a==0.)[0])
how_many_1 = len(np.where(a==1.)[0])

它还涉及一个步骤,但一种更灵活的解决方案(也适用于二维数组和更复杂的过滤器)是创建一个布尔掩码,然后在掩码上使用 .sum()。

>>>>y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
>>>>mask = y == 0
>>>>mask.sum()
8

使用 numpy.count_nonzero 怎么样,比如

>>> import numpy as np
>>> y = np.array([1, 2, 2, 2, 2, 0, 2, 3, 3, 3, 0, 0, 2, 2, 0])

>>> np.count_nonzero(y == 1)
1
>>> np.count_nonzero(y == 2)
7
>>> np.count_nonzero(y == 3)
3

过滤并使用len

使用 len 可能是另一种选择。

A = np.array([1,0,1,0,1,0,1])

假设我们想要 0.

的出现次数
A[A==0]  # Return the array where item is 0, array([0, 0, 0])

现在,用 len 环绕它。

len(A[A==0])  # 3
len(A[A==1])  # 4
len(A[A==7])  # 0, because there isn't such item.

就我个人而言,我会选择: (y == 0).sum()(y == 1).sum()

例如

import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
num_zeros = (y == 0).sum()
num_ones = (y == 1).sum()

y.tolist().count(val)

值为 0 或 1

由于 python 列表具有本机函数 count,因此在使用该函数之前转换为列表是一个简单的解决方案。

如果您不想使用 numpy 或集合模块,您可以使用字典:

d = dict()
a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
for item in a:
    try:
        d[item]+=1
    except KeyError:
        d[item]=1

结果:

>>>d
{0: 8, 1: 4}

当然你也可以使用if/else语句。 我认为 Counter 函数几乎做同样的事情,但它更透明。

另一个简单的解决方案可能是使用 numpy.count_nonzero():

import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
y_nonzero_num = np.count_nonzero(y==1)
y_zero_num = np.count_nonzero(y==0)
y_nonzero_num
4
y_zero_num
8

不要让名称误导了您,如果您像示例中那样将它与布尔值一起使用,它就可以解决问题。

这可以通过以下方法轻松完成

y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
y.tolist().count(1)

老实说,我发现转换为 pandas 系列或 DataFrame 最简单:

import pandas as pd
import numpy as np

df = pd.DataFrame({'data':np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])})
print df['data'].value_counts()

或者 Robert Muil 建议的这条漂亮的单线:

pd.Series([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]).value_counts()

一般而简单的答案是:

numpy.sum(MyArray==x)   # sum of a binary list of the occurence of x (=0 or 1) in MyArray

这将导致此完整代码作为示例

import numpy
MyArray=numpy.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])  # array we want to search in
x=0   # the value I want to count (can be iterator, in a list, etc.)
numpy.sum(MyArray==0)   # sum of a binary list of the occurence of x in MyArray

现在,如果 MyArray 在 多维 中,并且您想计算值分布的出现次数(= 下文中的模式)

MyArray=numpy.array([[6, 1],[4, 5],[0, 7],[5, 1],[2, 5],[1, 2],[3, 2],[0, 2],[2, 5],[5, 1],[3, 0]])
x=numpy.array([5,1])   # the value I want to count (can be iterator, in a list, etc.)
temp = numpy.ascontiguousarray(MyArray).view(numpy.dtype((numpy.void, MyArray.dtype.itemsize * MyArray.shape[1])))  # convert the 2d-array into an array of analyzable patterns
xt=numpy.ascontiguousarray(x).view(numpy.dtype((numpy.void, x.dtype.itemsize * x.shape[0])))  # convert what you search into one analyzable pattern
numpy.sum(temp==xt)  # count of the searched pattern in the list of patterns

统计出现的次数,可以使用np.unique(array, return_counts=True):

In [75]: boo = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
 
# use bool value `True` or equivalently `1`
In [77]: uniq, cnts = np.unique(boo, return_counts=1)
In [81]: uniq
Out[81]: array([0, 1])   #unique elements in input array are: 0, 1

In [82]: cnts
Out[82]: array([8, 4])   # 0 occurs 8 times, 1 occurs 4 times

因为你的 ndarray 只包含 0 和 1, 您可以使用 sum() 来获取 1 的出现 和 len()-sum() 得到 0 的出现。

num_of_ones = sum(array)
num_of_zeros = len(array)-sum(array)

没有人建议将 numpy.bincount(input, minlength)minlength = np.size(input) 一起使用,但这似乎是一个很好的解决方案,而且绝对是 最快的 :

In [1]: choices = np.random.randint(0, 100, 10000)

In [2]: %timeit [ np.sum(choices == k) for k in range(min(choices), max(choices)+1) ]
100 loops, best of 3: 2.67 ms per loop

In [3]: %timeit np.unique(choices, return_counts=True)
1000 loops, best of 3: 388 µs per loop

In [4]: %timeit np.bincount(choices, minlength=np.size(choices))
100000 loops, best of 3: 16.3 µs per loop

这是 numpy.unique(x, return_counts=True)numpy.bincount(x, minlength=np.max(x)) 之间的疯狂加速!

Numpy 有一个用于此的模块。只是一个小技巧。将您的输入数组作为垃圾箱。

numpy.histogram(y, bins=y)

输出是2个数组。一个具有值本身,另一个具有相应的频率。

如果您确切知道要查找的号码,可以使用以下方法;

lst = np.array([1,1,2,3,3,6,6,6,3,2,1])
(lst == 2).sum()

returns 2 在你的数组中出现了多少次。

对于通用条目:

x = np.array([11, 2, 3, 5, 3, 2, 16, 10, 10, 3, 11, 4, 5, 16, 3, 11, 4])
n = {i:len([j for j in np.where(x==i)[0]]) for i in set(x)}
ix = {i:[j for j in np.where(x==i)[0]] for i in set(x)}

将输出计数:

{2: 2, 3: 4, 4: 2, 5: 2, 10: 2, 11: 3, 16: 2}

和指数:

{2: [1, 5],
3: [2, 4, 9, 14],
4: [11, 16],
5: [3, 12],
10: [7, 8],
11: [0, 10, 15],
16: [6, 13]}

您可以使用字典理解来创建一个简洁的一行。有关字典理解的更多信息 can be found here

>>>counts = {int(value): list(y).count(value) for value in set(y)}
>>>print(counts)
{0: 8, 1: 4}

这将创建一个字典,将您的 ndarray 中的值作为键,并将值的计数分别作为键的值。

只要您想计算值在这种格式的数组中出现的次数,这就会起作用。

你有一个特殊的数组,这里只有 1 和 0。所以一个技巧是使用

np.mean(x)

它给出了数组中 1 的百分比。或者,使用

np.sum(x)
np.sum(1-x)

将为您提供数组中 1 和 0 的绝对数量。

利用系列提供的方法:

>>> import pandas as pd
>>> y = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
>>> pd.Series(y).value_counts()
0    8
1    4
dtype: int64
using numpy.count

$ a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]

$ np.count(a, 1)
dict(zip(*numpy.unique(y, return_counts=True)))

刚刚在这里复制了 Seppo Enarvi 的评论,这应该是一个正确的答案

试试这个:

a = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
list(a).count(1)

这里我有一个东西,你可以通过它计算某个数字出现的次数: 根据你的代码

count_of_zero=列表(y[y==0]).计数(0)

打印(count_of_zero)

// 根据匹配会有布尔值,根据真值数字 0 将是 return

如果您对最快的执行感兴趣,您事先知道要查找哪些值,并且您的数组是一维的,或者您对展平数组的结果感兴趣(在这种情况下函数的输入应该是 np.ravel(arr) 而不仅仅是 arr),那么 Numba 就是你的朋友:

import numba as nb


@nb.jit
def count_nb(arr, value):
    result = 0
    for x in arr:
        if x == value:
            result += 1
    return result

或者,对于并行化可能有益的非常大的阵列:

@nb.jit(parallel=True)
def count_nbp(arr, value):
    result = 0
    for i in nb.prange(arr.size):
        if arr[i] == value:
            result += 1
    return result

将这些与 np.count_nonzero() 进行基准测试(这也有创建一个可以避免的临时数组的问题)和基于 np.unique() 的解决方案

import numpy as np


def count_np(arr, value):
    return np.count_nonzero(arr == value)
import numpy as np


def count_np2(arr, value):
    uniques, counts = np.unique(a, return_counts=True)
    counter = dict(zip(uniques, counts))
    return counter[value] if value in counter else 0 

对于生成的输入:

def gen_input(n, a=0, b=100):
    return np.random.randint(a, b, n)

获得了以下图表(第二行图表是对更快方法的放大):

显示基于 Numba 的解决方案明显快于 NumPy 对应方案,并且对于非常大的输入,并行方法比原始方法更快。


完整代码可用 here

如果您要处理非常大的数组,使用生成器可能是一种选择。这里的好处是这种方法对数组和列表都适用,而且您不需要任何额外的包。此外,您没有使用那么多内存。

my_array = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
sum(1 for val in my_array if val==0)
Out: 8

这个函数 returns 变量在数组中出现的次数:

def count(array,variable):
    number = 0
    for i in range(array.shape[0]):
        for j in range(array.shape[1]):
            if array[i,j] == variable:
                number += 1
    return number