计算numpy.array中每行的出现次数

Aka*_*all 10 python arrays numpy pandas

我试图计算每行显示的数字np.array,例如:

import numpy as np
my_array = np.array([[1, 2, 0, 1, 1, 1],
                     [1, 2, 0, 1, 1, 1], # duplicate of row 0
                     [9, 7, 5, 3, 2, 1],
                     [1, 1, 1, 0, 0, 0], 
                     [1, 2, 0, 1, 1, 1], # duplicate of row 0
                     [1, 1, 1, 1, 1, 0]])
Run Code Online (Sandbox Code Playgroud)

[1, 2, 0, 1, 1, 1]显示3次.

一个简单的天真解决方案将涉及将我的所有行转换为元组,并应用collections.Counter,如下所示:

from collections import Counter
def row_counter(my_array):
    list_of_tups = [tuple(ele) for ele in my_array]
    return Counter(list_of_tups)
Run Code Online (Sandbox Code Playgroud)

产量:

In [2]: row_counter(my_array)
Out[2]: Counter({(1, 2, 0, 1, 1, 1): 3, (1, 1, 1, 1, 1, 0): 1, (9, 7, 5, 3, 2, 1): 1, (1, 1, 1, 0, 0, 0): 1})
Run Code Online (Sandbox Code Playgroud)

但是,我担心我的方法的效率.也许有一个库提供了这样做的内置方式.我将问题标记为pandas因为我认为pandas可能有我正在寻找的工具.

Jai*_*ime 11

您可以使用您的其他问题的答案来获取唯一项目的计数.

在numpy 1.9中有一个return_counts可选的关键字参数,所以你可以简单地做:

>>> my_array
array([[1, 2, 0, 1, 1, 1],
       [1, 2, 0, 1, 1, 1],
       [9, 7, 5, 3, 2, 1],
       [1, 1, 1, 0, 0, 0],
       [1, 2, 0, 1, 1, 1],
       [1, 1, 1, 1, 1, 0]])
>>> dt = np.dtype((np.void, my_array.dtype.itemsize * my_array.shape[1]))
>>> b = np.ascontiguousarray(my_array).view(dt)
>>> unq, cnt = np.unique(b, return_counts=True)
>>> unq = unq.view(my_array.dtype).reshape(-1, my_array.shape[1])
>>> unq
array([[1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0],
       [1, 2, 0, 1, 1, 1],
       [9, 7, 5, 3, 2, 1]])
>>> cnt
array([1, 1, 3, 1])
Run Code Online (Sandbox Code Playgroud)

在早期版本中,您可以这样做:

>>> unq, _ = np.unique(b, return_inverse=True)
>>> cnt = np.bincount(_)
>>> unq = unq.view(my_array.dtype).reshape(-1, my_array.shape[1])
>>> unq
array([[1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0],
       [1, 2, 0, 1, 1, 1],
       [9, 7, 5, 3, 2, 1]])
>>> cnt
array([1, 1, 3, 1])
Run Code Online (Sandbox Code Playgroud)


Yuy*_*ina 7

我认为只要指定axisin 就可以np.unique提供您需要的东西。

import numpy as np
unq, cnt = np.unique(my_array, axis=0, return_counts=True)
Run Code Online (Sandbox Code Playgroud)

注意:此功能仅在numpy>=1.13.0.


Ale*_*ley 5

(这假设数组相当小,例如少于 1000 行。)

这是一个简短的 NumPy 方法来计算每行在数组中出现的次数:

>>> (my_array[:, np.newaxis] == my_array).all(axis=2).sum(axis=1)
array([3, 3, 1, 1, 3, 1])
Run Code Online (Sandbox Code Playgroud)

这计算每行出现的次数my_array,返回一个数组,其中第一个值显示第一行出现的次数,第二个值显示第二行出现的次数,依此类推。