Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

python - Translate integers in a numpy array to a contiguous range 0...n

I would like to translate arbitrary integers in a numpy array to a contiguous range 0...n, like 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 be a better way to than the following:

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

What is it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IIUC you can simply use np.unique's optional argument return_inverse, like so -

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...