Python 根据规则替换多维numpy数组的元素

Python 根据规则替换多维numpy数组的元素,python,arrays,numpy,multidimensional-array,replace,Python,Arrays,Numpy,Multidimensional Array,Replace,假设我们有一个numpy数组: import numpy as np arr = np.array([[ 5, 9],[14, 23],[26, 4],[ 5, 26]]) 我想用每个元素的出现次数替换每个元素 unique0, counts0= np.unique(arr.flatten(), return_counts=True) print (unique0, counts0) 数组[4,5,9,14,23,26],数组[1,2,1,1,1,1,2] 因此,应将4替换为1,将5

假设我们有一个numpy数组:

import numpy as np
arr = np.array([[ 5,  9],[14, 23],[26,  4],[ 5, 26]])
我想用每个元素的出现次数替换每个元素

 unique0, counts0= np.unique(arr.flatten(), return_counts=True)
 print (unique0, counts0)
数组[4,5,9,14,23,26],数组[1,2,1,1,1,1,2]

因此,应将4替换为1,将5替换为2,以此类推,以获得:

[2,1],[1,1],[2,1],[2,2]]


有没有办法在numpy中实现这一点?

使用另一个可选参数return\u inverse with根据元素的唯一性标记所有元素,然后将这些元素与计数进行映射,以提供我们所需的输出,如下所示-

_, idx, counts0 = np.unique(arr, return_counts=True,return_inverse=True)
out = counts0[idx].reshape(arr.shape)
样本运行-

In [100]: arr
Out[100]: 
array([[ 5,  9],
       [14, 23],
       [26,  4],
       [ 5, 26]])

In [101]: _, idx, counts0 = np.unique(arr, return_counts=True,return_inverse=True)

In [102]: counts0[idx].reshape(arr.shape)
Out[102]: 
array([[2, 1],
       [1, 1],
       [2, 1],
       [2, 2]])

这是另一种解决方案,因为@Divakar的答案在另一种版本中不起作用!此外,您还可以使用.ravel而不是.flatte,这样可以避免复制,从而提高性能。
 In [1]: import numpy as np

 In [2]: arr = np.array([[ 5,  9],[14, 23],[26,  4],[ 5, 26]])

 In [3]: np.bincount(arr.flatten())[arr]
 Out[3]: 
 array([[2, 1],
        [1, 1],
        [2, 1],
        [2, 2]])
def replace_unique(arr):
    _, idx, counts0 = np.unique(arr,return_counts=True,return_inverse=True)
    return counts0[idx].reshape(arr.shape)

def replace_bincount(arr):
    return np.bincount(arr.flatten())[arr]

arr = np.random.random_integers(30,size=[10000,2])


%timeit -n 1000 replace_bincount(arr)
# 1000 loops, best of 3: 68.3 µs per loop
%timeit -n 1000 replace_unique(arr)
# 1000 loops, best of 3: 922 µs per loop