i translate arbitrary integers in numpy array contiguous range 0...n, this:
source: [2 3 4 5 4 3] translating [2 3 4 5] -> [0 1 2 3] target: [0 1 2 3 2 1]
there must better way following:
import numpy np "translate arbitrary integers in source array contiguous range 0...n" def translate_ids(source, source_ids, target_ids): target = source.copy() 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
what it?
iiuc can use np.unique
's optional argument return_inverse
, -
np.unique(source,return_inverse=true)[1]
sample run -
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])
Comments
Post a Comment