问题指出输入数组的形状
(128, 36,8),我们有兴趣在
8最后一个维度中找到长度唯一的子数组。因此,我假设唯一性是沿着合并在一起的前两个维度。让我们假设
A作为输入3D阵列。
获取唯一子数组的数量
# Reshape the 3D array to a 2D array merging the first two dimensionsAr = A.reshape(-1,A.shape[2])# Perform lex sort and get the sorted indices and xy pairssorted_idx = np.lexsort(Ar.T)sorted_Ar = Ar[sorted_idx,:]# Get the count of rows that have at least one TRUE value # indicating presence of unique subarray thereunq_out = np.any(np.diff(sorted_Ar,axis=0),1).sum()+1
样品运行-
In [159]: A # A is (2,2,3)Out[159]: array([[[0, 0, 0], [0, 0, 2]], [[0, 0, 2], [2, 0, 1]]])In [160]: unq_outOut[160]: 3
获取唯一子数组的出现次数
# Reshape the 3D array to a 2D array merging the first two dimensionsAr = A.reshape(-1,A.shape[2])# Perform lex sort and get the sorted indices and xy pairssorted_idx = np.lexsort(Ar.T)sorted_Ar = Ar[sorted_idx,:]# Get IDs for each element based on their uniquenessid = np.append([0],np.any(np.diff(sorted_Ar,axis=0),1).cumsum())# Get counts for each ID as the final outputunq_count = np.bincount(id)
样品运行-
In [64]: AOut[64]: array([[[0, 0, 2], [1, 1, 1]], [[1, 1, 1], [1, 2, 0]]])In [65]: unq_countOut[65]: array([1, 2, 1], dtype=int64)



