Python 计算numpy数组中列的出现次数
给定一个2d维numpy数组M,我想计算M的每一列出现的次数。也就是说,我正在寻找的是的一般版本 到目前为止,我尝试的是:(1)将列转换为元组(2)将哈希元组(通过Python 计算numpy数组中列的出现次数,python,numpy,Python,Numpy,给定一个2d维numpy数组M,我想计算M的每一列出现的次数。也就是说,我正在寻找的是的一般版本 到目前为止,我尝试的是:(1)将列转换为元组(2)将哈希元组(通过hash)转换为自然数(3)使用numpy.bincount 这似乎相当笨拙。有人知道一种更优雅、更高效的方法吗?给出: a = np.array([[ 0, 1, 2, 4, 5, 1, 2, 3], [ 4, 5, 6, 8, 9, 5, 6, 7],
hash
)转换为自然数(3)使用numpy.bincount
这似乎相当笨拙。有人知道一种更优雅、更高效的方法吗?给出:
a = np.array([[ 0, 1, 2, 4, 5, 1, 2, 3],
[ 4, 5, 6, 8, 9, 5, 6, 7],
[ 8, 9, 10, 12, 13, 9, 10, 11]])
b = np.transpose(a)
np.void
(请参见)创建了一个数组视图,以便每一行都成为一个元素。转换为此形状将允许np.unique
对其进行操作
%%timeit
c = np.ascontiguousarray(b).view(np.dtype((np.void, b.dtype.itemsize*b.shape[1])))
_, index, counts = np.unique(c, return_index = True, return_counts = True)
#counts are in the last column, remember original array is transposed
>>>np.concatenate((b[idx], cnt[:, None]), axis = 1)
array([[ 0, 4, 8, 1],
[ 1, 5, 9, 2],
[ 2, 6, 10, 2],
[ 3, 7, 11, 1],
[ 4, 8, 12, 1],
[ 5, 9, 13, 1]])
10000 loops, best of 3: 65.4 µs per loop
附加到a
的唯一列的计数%%timeit
array_hash = [hash(tuple(row)) for row in b]
uniq, index, counts = np.unique(array_hash, return_index= True, return_counts = True)
np.concatenate((b[idx], cnt[:, None]), axis = 1)
10000 loops, best of 3: 89.5 µs per loop
%%timeit
Counter(map(tuple, a.T))
10000 loops, best of 3: 38.3 µs per loop
您可以使用集合。计数器:
>>> import numpy as np
>>> a = np.array([[ 0, 1, 2, 4, 5, 1, 2, 3],
... [ 4, 5, 6, 8, 9, 5, 6, 7],
... [ 8, 9, 10, 12, 13, 9, 10, 11]])
>>> from collections import Counter
>>> Counter(map(tuple, a.T))
Counter({(2, 6, 10): 2, (1, 5, 9): 2, (4, 8, 12): 1, (5, 9, 13): 1, (3, 7, 11):
1, (0, 4, 8): 1})
有趣的问题。期待看到任何解决方案,因为我的第一个也是唯一一个想法就是你所做的。那么你期待一个独特列及其计数的列表?是否必须保留列的顺序?请显示您尝试的代码。如果是3d数组,我如何执行相同操作。基本上,我有一个3通道图像,所以在上面的示例中,我没有使用每个元素,而是使用3个数字。