我有一个 numpy 数组。我想重新调整数组中的元素,使数组中的最小数字用 1 表示,数组中的最大数字用数组中唯一元素的数量表示。
例如
A=[ [2,8,8],[3,4,5] ]
会成为
[ [1,5,5],[2,3,4] ]
我有一个 numpy 数组。我想重新调整数组中的元素,使数组中的最小数字用 1 表示,数组中的最大数字用数组中唯一元素的数量表示。
例如
A=[ [2,8,8],[3,4,5] ]
会成为
[ [1,5,5],[2,3,4] ]
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]])
如果您不反对使用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'
将获得相同的结果,有关更多详细信息,请参阅链接文档