1

我有一个 numpy 数组。我想重新调整数组中的元素,使数组中的最小数字用 1 表示,数组中的最大数字用数组中唯一元素的数量表示。

例如

A=[ [2,8,8],[3,4,5] ]  

会成为

[ [1,5,5],[2,3,4] ]
4

2 回答 2

3

np.unique与其return_inverse参数一起使用-

np.unique(A, return_inverse=1)[1].reshape(A.shape)+1

样品运行 -

In [10]: A
Out[10]: 
array([[2, 8, 8],
       [3, 4, 5]])

In [11]: np.unique(A, return_inverse=1)[1].reshape(A.shape)+1
Out[11]: 
array([[1, 5, 5],
       [2, 3, 4]])
于 2018-06-07T19:43:24.717 回答
1

如果您不反对使用scipy, 您可以使用rankdata, with method='dense'(根据您问题上的标签判断):

from scipy.stats import rankdata

rankdata(A, 'dense').reshape(A.shape)

array([[1, 5, 5],
       [2, 3, 4]])

请注意,在您的情况下,method='min'将获得相同的结果,有关更多详细信息,请参阅链接文档

于 2018-06-07T19:49:19.990 回答