这个答案背后的想法非常类似于
used here.我在每行添加一个独特的虚数.因此,来自不同行的两个数字不能相等.因此,只需调用一次np.unique,就可以在每行的2D数组中找到所有唯一值.
当return_index = True时返回索引ind,它为您提供每个唯一值第一次出现的位置.
当return_counts = True时返回的计数cnt给你计数.
np.put(b, ind, cnt)将计数放在每个唯一值的第一个出现位置.
这里使用的技巧的一个明显限制是原始数组必须具有int或float dtype.它不能以复杂的dtype开头,因为将每一行乘以一个唯一的虚数可能会产生来自不同行的重复对.
import numpy as np
a = np.array([[1, 2, 2, 3, 4, 5],
[1, 2, 3, 3, 4, 5],
[1, 2, 3, 4, 4, 5],
[1, 2, 3, 4, 5, 5],
[1, 2, 3, 4, 5, 6]])
def count_unique_by_row(a):
weight = 1j*np.linspace(0, a.shape[1], a.shape[0], endpoint=False)
b = a + weight[:, np.newaxis]
u, ind, cnt = np.unique(b, return_index=True, return_counts=True)
b = np.zeros_like(a)
np.put(b, ind, cnt)
return b
产量
In [79]: count_unique_by_row(a)
Out[79]:
array([[1, 2, 0, 1, 1, 1],
[1, 1, 2, 0, 1, 1],
[1, 1, 1, 2, 0, 1],
[1, 1, 1, 1, 2, 0],
[1, 1, 1, 1, 1, 1]])