Skip to main content
 首页 » 编程设计

python之将 numpy 数组中的整数转换为连续范围 0...n

2025年05月04日23mfryf

我想将 numpy 数组中的任意整数转换为连续范围 0...n,如下所示:

source: [2 3 4 5 4 3] 
translating [2 3 4 5] -> [0 1 2 3] 
target: [0 1 2 3 2 1] 

必须有比以下更好的方法:

import numpy as np 
 
"translate arbitrary integers in the source array to contiguous range 0...n" 
 
def translate_ids(source, source_ids, target_ids): 
    target = source.copy() 
 
    for i in range(len(source_ids)): 
        x = source_ids[i] 
        x_i = source == x 
        target[x_i] = target_ids[i] 
 
    return target 
 
# 
 
source = np.array([ 2, 3, 4, 5, 4, 3 ]) 
source_ids = np.unique(source) 
target_ids = np.arange(len(source_ids)) 
 
target = translate_ids(source, source_ids, target_ids) 
 
print "source:", source 
print "translating", source_ids, '->', target_ids 
print "target:", target 

这是什么?

请您参考如下方法:

IIUC 你可以简单地使用 np.unique的可选参数 return_inverse,像这样 -

np.unique(source,return_inverse=True)[1] 

sample 运行-

In [44]: source 
Out[44]: array([2, 3, 4, 5, 4, 3]) 
 
In [45]: np.unique(source,return_inverse=True)[1] 
Out[45]: array([0, 1, 2, 3, 2, 1])