Python : 将值无间隙地映射到其他值
Python : Mapping values to other values without gap
我有以下问题。有没有 numpy 或 scipy 的某种方法,我可以使用它来获取给定的未排序数组,例如
a = np.array([0,0,1,1,4,4,4,4,5,1891,7]) #could be any number here
对于数字为 interpolated/mapped 的东西,值之间没有间隙并且它们的顺序与以前相同?:
[0,0,1,1,2,2,2,2,3,5,4]
编辑
是否还有可能swap/shuffle映射后的数字,使得
[0,0,1,1,2,2,2,2,3,5,4]
变成类似:
[0,0,3,3,5,5,5,5,4,1,2]
编辑:我不确定这里的礼仪是什么(这应该是一个单独的答案吗?),但这实际上可以直接从 np.unique
.
获得
>>> u, indices = np.unique(a, return_inverse=True)
>>> indices
array([0, 0, 1, 1, 2, 2, 2, 2, 3, 5, 4])
原始答案:通过构建数组的每个值将映射到的索引的字典,这在普通 python 中并不难做到:
x = np.sort(np.unique(a))
index_dict = {j: i for i, j in enumerate(x)}
[index_dict[i] for i in a]
似乎您需要 rank
(密集)您的阵列,在这种情况下使用 scipy.stats.rankdata
:
from scipy.stats import rankdata
rankdata(a, 'dense')-1
# array([ 0., 0., 1., 1., 2., 2., 2., 2., 3., 5., 4.])
我有以下问题。有没有 numpy 或 scipy 的某种方法,我可以使用它来获取给定的未排序数组,例如
a = np.array([0,0,1,1,4,4,4,4,5,1891,7]) #could be any number here
对于数字为 interpolated/mapped 的东西,值之间没有间隙并且它们的顺序与以前相同?:
[0,0,1,1,2,2,2,2,3,5,4]
编辑
是否还有可能swap/shuffle映射后的数字,使得
[0,0,1,1,2,2,2,2,3,5,4]
变成类似:
[0,0,3,3,5,5,5,5,4,1,2]
编辑:我不确定这里的礼仪是什么(这应该是一个单独的答案吗?),但这实际上可以直接从 np.unique
.
>>> u, indices = np.unique(a, return_inverse=True)
>>> indices
array([0, 0, 1, 1, 2, 2, 2, 2, 3, 5, 4])
原始答案:通过构建数组的每个值将映射到的索引的字典,这在普通 python 中并不难做到:
x = np.sort(np.unique(a))
index_dict = {j: i for i, j in enumerate(x)}
[index_dict[i] for i in a]
似乎您需要 rank
(密集)您的阵列,在这种情况下使用 scipy.stats.rankdata
:
from scipy.stats import rankdata
rankdata(a, 'dense')-1
# array([ 0., 0., 1., 1., 2., 2., 2., 2., 3., 5., 4.])