Skip to main content
 首页 » 编程设计

python之在 ndarray 中逐行计算唯一元素

2025年05月04日12zengkefu

this 的扩展问题。除了按行排列唯一元素外,我还希望有一个形状相似的数组来计算唯一值的数量。例如,如果初始数组如下所示:

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]]) 

我想将其作为函数的输出:

np.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]]) 

在 numpy v.1.9 中似乎有一个额外的参数 return_counts 可以返回扁平数组中的计数。有什么方法可以将其重新构造为原始数组维度,其中值重复的值为零?

请您参考如下方法:

这个答案背后的想法与 used here 非常相似.我在每一行中添加了一个唯一的虚数。因此,来自不同行的两个数字不可能相等。因此,只需调用 np.unique 一次,您就可以每行 找到二维数组中的所有唯一值。

当 return_index=True 为您提供每个唯一值第一次出现的位置时,返回的索引 ind。

计数 cnt,当 return_counts=True 给出计数时返回。

np.put(b, ind, cnt)将计数放在每个唯一值第一次出现的位置。

此处使用的技巧的一个明显限制是原始数组必须具有 int 或 float 数据类型。它不能以复杂的 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]])